Skip to main content

Operators and Operator Precedence In JavaScript

operators-and-operator-precedence-in-javascript

Operators and Operator Precedence In JavaScript

In JavaScript, precedence determines the order in which operators are evaluated in an expression. Understanding operator precedence is crucial for writing correct and predictable JavaScript code. It is recommended to use parentheses when necessary to clarify the intended order of operation. Operators with higher precedence are evaluated first. Here are some examples of operator precedence in JavaScript:


Arithmetic Operators

Multiplication, division, and modulo operators have higher precedence than addition and subtraction.

console.log(3+4*5);

Output:

23

As multiplication is performed first.


Comparison Operators

Comparison operators such as <, >, <=, and >= have higher precedence than equality operators like == and ===.

console.log(2 + 3 < 4 * 5);

Output:

True

Evaluates to true because the comparison is evaluated before addition.


Logical Operators

Logical NOT (!) has the highest precedence, followed by logical AND (&&), and logical OR (||) has the lowest precedence.

console.log(!true && false || true);

Output:

True

Evaluates to true because the NOT operator is evaluated first, followed by the AND and OR operators.


Assignment Operators

Assignment operators, such as =, +=, -= have a lower precedence compared to arithmetic and logical operators.

var x = 2 + 3
console.log(x);

Output:

5

assigns the value 5 to the variable x after performing the addition operation.


Grouping with Parentheses

Parentheses can be used to enforce a specific order of evaluation, overriding the default precedence rules.

var x = (2 + 3) * 4
console.log(x);

Output:

20

evaluates to 20 because the addition inside the parentheses is performed first.


Comments