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:
- Grouping:
() - Member Access:
. - Function Call:
() - Increment/Decrement:
++,-- - Logical NOT / Bitwise NOT:
!,~ - Unary Plus/Minus:
+,- - Multiplication/Division/Modulus:
*,/,% - Addition/Subtraction:
+,- - Relational Operators:
<,>,<=,>= - Equality Operators:
==,!=,===,!== - Logical AND:
&& - Logical OR:
|| - Conditional (Ternary):
condition ? expr1 : expr2 - 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.