Understanding JavaScript Operator Precedence: A Comprehensive Guide

Understanding JavaScript Operator Precedence

Operator precedence in JavaScript determines the order in which different operators are evaluated in expressions. Understanding operator precedence is crucial for writing correct and predictable code.

Key Concepts

  • Operator Precedence: Refers to the rules that determine the sequence in which operators are applied in an expression.
  • Higher Precedence: Operators with higher precedence are evaluated before those with lower precedence.
  • Associativity: The direction in which operators of the same precedence level are evaluated (left-to-right or right-to-left).

Precedence Levels

Here are some common operators and their precedence levels (from highest to lowest):

  1. Parentheses (): Highest precedence. Used to group expressions.
    • Example: (2 + 3) * 4 evaluates to 20, not 14.
  2. Exponentiation **: Evaluates powers.
    • Example: 2 ** 3 evaluates to 8.
  3. Multiplication *, Division /, and Modulus %: Evaluated next, from left to right.
    • Example: 10 / 2 * 3 evaluates to 15.
  4. Addition + and Subtraction -: Evaluated after multiplication and division, from left to right.
    • Example: 5 + 3 - 2 evaluates to 6.
  5. Comparison Operators: Such as <, >, <=, and >= are evaluated after arithmetic operators.
    • Example: 5 * 2 > 7 evaluates to true.

Examples

Example 3:

let result = 10 - 4 + 2; // Result is 8, evaluated from left to right.

Example 2:

let result = (5 + 3) * 2; // Result is 16, because parentheses are evaluated first.

Example 1:

let result = 5 + 3 * 2; // Result is 11, because multiplication is evaluated first.

Conclusion

Understanding operator precedence and associativity helps prevent mistakes in JavaScript coding. Always use parentheses to make expressions clearer and to control the order of evaluation when necessary.