What are JavaScript operators precedence and associativity
· Category: JavaScript
Short answer
Operator precedence determines which operator is evaluated first, while associativity determines the order for operators of the same precedence level.
How it works
Higher precedence operators bind tighter. Key levels (high to low):
- Grouping
() - Member access
.and[], function call() - Unary operators
!,typeof,++,-- - Multiplicative
*,/,% - Additive
+,- - Relational
<,<=,>,>= - Equality
==,=== - Logical AND
&& - Logical OR
|| - Assignment
=(right-associative)
Example
const a = 2 + 3 * 4; // 14, not 20
const b = 10 - 4 - 2; // 4 (left-associative)
const c = a = b = 1; // c = 1 (right-associative)
Why it matters
Misunderstanding precedence causes silent bugs. Use parentheses to make intent explicit and improve readability, especially with mixed logical and arithmetic operators.