JavaScript Operator Precedence

Subject: JavaScript

Operator precedence defines the order in which JavaScript evaluates operators in an expression. When multiple operators are used together, JavaScript uses this precedence to determine which operation to perform first.

Understanding precedence ensures you avoid unexpected results in expressions and write more accurate code.


What Is Operator Precedence?

When an expression includes multiple operators, JavaScript follows a priority list, starting from the highest precedence to the lowest.

Example:

Here, multiplication (*) is performed before addition (+), even though + appears first — because * has higher precedence.


Operator Precedence Order (High to Low)

Here is a simplified list of commonly used operators by precedence:

  1. Grouping: ()
  2. Member Access: .
  3. Function Call: ()
  4. Increment/Decrement: ++, --
  5. Logical NOT / Bitwise NOT: !, ~
  6. Unary Plus/Minus: +, -
  7. Multiplication/Division/Modulus: *, /, %
  8. Addition/Subtraction: +, -
  9. Relational Operators: <, >, <=, >=
  10. Equality Operators: ==, !=, ===, !==
  11. Logical AND: &&
  12. Logical OR: ||
  13. Conditional (Ternary): condition ? expr1 : expr2
  14. Assignment: =, +=, -=, etc.

Associativity

Associativity determines the order in which operators of the same precedence are evaluated. It can be:

  • Left-to-right (most operators)
  • Right-to-left (e.g., assignment, exponentiation)

Example: Left-to-right

Example: Right-to-left


Use Parentheses to Control Precedence

When in doubt, use parentheses () to make precedence explicit and improve readability.

Without parentheses: 10 + 5 * 2 → 20 With parentheses: (10 + 5) * 2 → 30


Key Takeaways

  • Operator precedence defines the order of execution for different operators.
  • Use parentheses () to override or clarify precedence.
  • Associativity decides the direction in which operators of the same precedence execute.
  • Misunderstanding precedence can cause unexpected bugs, especially in complex expressions.
  • Always write readable expressions rather than relying only on precedence rules.
Next : Arithmetic Operators