Operator Precedence & Associativity
The rules that decide who binds first -- and why parentheses beat memorising all of them.
Syntax
grouping () > ** (right) > * / % > + - > comparisons > && > || > ??Precedence decides which operator grabs its operands first; associativity breaks ties between operators of equal precedence.
The handful worth internalising
- Member access
.?.and calls()bind tightest. **is right-associative and outranks unary minus, so-2 ** 2is a syntax error on purpose -- write-(2 ** 2)or(-2) ** 2.*/%beat+-.- Comparisons beat
&&, which beats||, which beats??(they cannot even mix without parens). - Assignment and the comma operator are near the bottom.
2 + 3 * 4 // 14, not 20
a || b && c // a || (b && c)
!x === y // (!x) === yThe senior move
Nobody recalls all 19 tiers under pressure. Add parentheses the moment an expression mixes families of operators. The compiler does not care; the next human does.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Add explicit parentheses around a bitwise AND expression used inside a logical OR to avoid precedence bugs.
- Understand why a calculation produces an unexpected result when * and + are mixed without parentheses.
- Use parentheses to force a string concatenation to happen before an addition in a mixed expression.
More examples
Arithmetic precedence
Multiplication has higher precedence than addition; parentheses override the default order.
console.log(2 + 3 * 4); // 14 β * before +
console.log((2 + 3) * 4); // 20 β parens overrideComparison and logical precedence
AND binds tighter than OR; the first expression evaluates b&&c first, then ORs with a.
const a = true, b = false, c = true;
console.log(a || b && c); // true β && before ||
console.log((a || b) && c); // true β same here by chance
console.log(false || false && true); // falseAssignment vs equality in a condition
Shows that assignment = has lower precedence than ===; extra parens make the intent explicit.
let x = 0;
// if (x = 5) { ... } // assignment in condition β always truthy!
if ((x = 5) === 5) {
console.log("x is", x); // "x is 5"
}
Discussion