Sub topic 2
Who Goes First: Precedence and Associativity
This chapter assumes you can declare variables with let and const, write and call functions, and run snippets in a browser console or Node.js. You should also be familiar with the basic arithmetic and comparison operators. Later chapters cover how each operator converts its operands. Here the question is narrower: when an expression has several operators, which ones are applied first?
Two Rules That Decide Grouping
JavaScript decides how to group an expression with two rules.
- Precedence is a ranking of operators. When two different operators compete for the same operand, the one with higher precedence binds to it first.
- Associativity settles ties. When two operators of equal precedence compete, associativity decides whether they group from the left or from the right.
console.log(2 + 3 * 4); // 14
console.log((2 + 3) * 4); // 20
console.log(2 ** 3 ** 2); // 512, because ** is right-associative: 2 ** 9
console.log((-2) ** 2); // 4
// -2 ** 2 is a SyntaxError: a unary operator cannot appear directly before **In 2 + 3 * 4, the * operator has higher precedence than +, so the parser groups the expression as 2 + (3 * 4). Parentheses override precedence, which is why (2 + 3) * 4 gives 20.
The expression 2 ** 3 ** 2 has two operators of the same precedence. Exponentiation is right-associative, so it groups as 2 ** (3 ** 2), which is 2 ** 9, or 512. Most other binary operators are left-associative. For example, 10 - 4 - 3 means (10 - 4) - 3, which is 3, not 9.
Grouping Is a Tree
The parser turns an expression into a tree. Operators with higher precedence end up deeper in the tree, so they are computed before the operators above them.
Grouping Is Not Evaluation Order
Many developers get this point wrong. Precedence decides how operands are grouped. It does not decide which operand expression runs first. JavaScript evaluates operands from left to right, and then it applies operators according to the tree.
function log(label, value) {
console.log(label);
return value;
}
const result = log('A', 2) + log('B', 3) * log('C', 4);
console.log(result);
// Output:
// A
// B
// C
// 14The multiplication happens before the addition, but log('A', 2) still runs first. This matters when operands have side effects, such as function calls that change state, ++, or assignments inside expressions.
The Precedence Table You Actually Need
You don't need to memorize the full table. The rows below cover most of the code you will read, ordered from highest precedence to lowest.
| Level (high to low) | Operators | Associativity | Column | Column |
|---|---|---|---|---|
| Grouping | `( ... )` | n/a | ||
| Member access and calls | `.` `[]` `?.` `f()` `new X()` | left | ||
| Postfix | `x++` `x--` | n/a | ||
| Prefix and unary | `!` `~` `+x` `-x` `++x` `--x` `typeof` `void` `delete` `await` | right | ||
| Exponentiation | `**` | right | ||
| Multiplicative | `*` `/` `%` | left | ||
| Additive | `+` `-` | left | ||
| Shift | `<<` `>>` `>>>` | left | ||
| Relational | `<` `<=` `>` `>=` `in` `instanceof` | left | ||
| Equality | `==` `!=` `===` `!==` | left | ||
| Bitwise AND, XOR, OR | `&`, then `^`, then `\ | ` | left | |
| Logical AND | `&&` | left | ||
| Logical OR and nullish | `\ | \ | ` `??` | left |
| Conditional and assignment | `? :` `=` `+=` `&&=` `??=` and others | right | ||
| Comma | `,` | left |
Here is a rough guide: arithmetic binds tighter than comparison, comparison binds tighter than logic, and assignment binds loosest of all except the comma operator.
Common Precedence Traps
Unary operators bind tighter than you expect
Unary operators such as ! and typeof apply to the smallest operand next to them.
const items = [];
console.log(!items instanceof Array); // false: (!items) instanceof Array
console.log(!(items instanceof Array)); // false, but for the right reason
console.log(typeof 1 + 2); // 'number2': (typeof 1) + 2
console.log(typeof (1 + 2)); // 'number'The first line checks whether the boolean false is an instance of Array. That check is always false, whatever items holds.
Unary minus and exponentiation
In mathematics, -2² usually means -(2²). Other languages pick different conventions, so JavaScript refuses to guess. It throws a SyntaxError when a unary operator appears directly before the left operand of **.
console.log((-2) ** 2); // 4
console.log(-(2 ** 2)); // -4
console.log(2 ** -1); // 0.5: a unary operator on the right operand is allowedAssignment is right-associative
Because assignment groups from the right, a = b = 5 means a = (b = 5). An assignment expression evaluates to the value it assigned.
let a;
let b;
a = b = 5;
console.log(a, b); // 5 5Chained conditionals
The conditional operator is also right-associative, so a chain of ? : reads like an if...else if ladder.
const score = 72;
const grade = score >= 90 ? 'A' : score >= 70 ? 'B' : 'C';
console.log(grade); // 'B'The condition binds more loosely than almost everything else. That means a + b ? x : y tests the sum a + b, not b.
Mixing && and ||
&& has higher precedence than ||, so a || b && c means a || (b && c).
console.log(true || false && false); // true
console.log((true || false) && false); // false?? refuses to mix
The nullish coalescing operator ?? cannot be combined directly with && or ||. You must add parentheses, or the code throws a SyntaxError. The chapter on ?? covers this rule in more detail.
The comma operator
The comma operator evaluates each operand from left to right and returns the last one. It has the lowest precedence, so it usually needs parentheses.
const x = (console.log('side effect'), 42);
console.log(x); // 42How to Choose: Parentheses or Not
Parentheses cost nothing at runtime, so the decision is only about readability.
- Leave them out when the grouping is universally known, as in
a + b * corx === y && ready. - Add them when you mix operator families that readers rarely rank correctly:
&&with||, bitwise with comparison,!withinstanceoforin, and any use of the conditional operator inside a larger expression. - Always add them where the language requires them: a unary operator before
**, and??mixed with&&or||.
Exercises
Exercise
What does console.log(1 + 2 * 3 ** 2 - 4) print, and how is it grouped?
Show answer
It prints 15. The grouping is (1 + (2 * (3 ** 2))) - 4. First 3 * 2 is 9, then 2 9 is 18, then 1 + 18 is 19, and 19 - 4 is 15. Addition and subtraction have equal precedence and group from the left.
Exercise
A teammate writes if (!key in config) { ... } to run code when config lacks key. Why is this a bug, and how do you fix it?
Show answer
! binds tighter than in, so the condition is (!key) in config. It checks for a property named "true" or "false", depending on whether key is truthy. The fix is if (!(key in config)) { ... }.
Exercise
Given let i = 1; const r = i++ + i * i;, what is r, and why does precedence alone not answer the question?
Show answer
r is 5. Operands are evaluated from left to right. i++ yields 1 and sets i to 2, then i * i is 2 2, or 4, and 1 + 4 is 5. Precedence only says that ` groups before +. Left-to-right operand evaluation decides when the side effect of i++` becomes visible.