JavaScript : Operator Precedence

Operator precedence determines the order in which operators are evaluated in an expression. JavaScript follows a set of rules to determine the precedence of operators when evaluating expressions. Here's an overview of the operator precedence in JavaScript:

Highest Precedence:


1. Grouping: ( )

  •    Parentheses are used to override the default precedence and force evaluation of expressions inside them first.

Unary Operators:


2. Unary Plus ( + ) and Unary Negation ( - )

  •    Unary plus and minus operators are used to convert their operand into a number, and the order of evaluation is from right to left.

3. Logical NOT ( ! )

  •   The logical NOT operator is used to invert the value of its operand.

4. Bitwise NOT ( ~ )

  •    The bitwise NOT operator inverts all bits in its operand.

5. Typeof

  •    The typeof operator is used to determine the data type of its operand.

6. Void

  •    The void operator discards the result of an expression and evaluates to undefined .

Multiplicative Operators:


7. Multiplication ( * ), Division ( / ), and Remainder ( %)

  •    Multiplication, division, and remainder operators are evaluated from left to right.

 Additive Operators:


8. Addition ( + ) and Subtraction ( - )

  •    Addition and subtraction operators are evaluated from left to right.

 Bitwise Shift Operators:


9. Left Shift ( << ), Right Shift ( >> ), and Unsigned Right Shift ( >>> )

  •    Bitwise shift operators are evaluated from left to right.

Relational Operators:


10. Less Than ( < ), Less Than or Equal To ( <= ), Greater Than ( > ), and Greater Than or Equal To ( >= )

  •    Relational operators are evaluated from left to right.

Equality Operators:


11. Equality ( == and != ), Strict Equality ( === and !== )

  •    Equality operators are evaluated from left to right.

Bitwise Operators:


12. Bitwise AND ( & ), Bitwise XOR ( ^ ), and Bitwise OR ( | )

  •    Bitwise operators are evaluated from left to right.

Logical Operators:


13. Logical AND ( && ) and Logical OR ( || )

  •  Logical operators are evaluated from left to right, but they short-circuit, meaning they only evaluate the second operand if necessary.

Conditional (Ternary) Operator:


14. Ternary ( ?: )

  •     The ternary operator is evaluated from left to right.

Assignment Operators:


15. Assignment ( = ) and Compound Assignment ( += , -= , *= , /= , etc.)

  •     Assignment operators are evaluated from right to left.

Lowest Precedence:


Operators with higher precedence are evaluated before operators with lower precedence. If operators have the same precedence, they are evaluated from left to right (except for assignment operators, which are evaluated from right to left).

Understanding operator precedence is crucial for writing expressions that behave as expected. It helps in avoiding errors and ensures that expressions are evaluated correctly.