← Back to JavaScript, page 8

javascript-0153 · Easy fresher

How do operator precedence and associativity work in JavaScript, and which cases surprise people?

Precedence decides which operator in an expression is applied first, and associativity decides the direction for operators of the same level. Multiplication runs before addition, the exponent operator is right associative, and && binds tighter than ||. Mixing ?? with || or && without parentheses is a syntax error, and the increment operators and the ternary have surprising results, so use parentheses when it helps readers.

Full answer

Precedence is a ranking. In 2 + 3 * 4, multiplication has higher precedence than addition, so the result is 14. Parentheses override any precedence. Associativity applies when two operators have equal precedence: most operators are left associative (10 - 4 - 3 is (10 - 4) - 3, which is 3), but assignment, the ternary, and ** are right associative (2 ** 3 ** 2 is 2 ** (3 ** 2), which is 512).

A useful order from high to low:

  1. Member access and calls: a.b, a[b], f(), new X().
  2. Postfix and prefix ++ and --, unary !, -, +, typeof, void, delete, await.
  3. **.
  4. *, /, %, then + and -.
  5. Shifts, then relational (<, >, in, instanceof), then equality (==, ===).
  6. Bitwise &, ^, |.
  7. &&, then || and ??.
  8. Ternary ? :, then assignment, then the comma.

Cases that surprise people:

  • && binds tighter than ||: true || false && false is true because it reads true || (false && false).
  • ?? cannot be mixed with || or && without parentheses. Writing a ?? b || c is a SyntaxError on purpose, to avoid confusion.
  • A unary minus before ** is not allowed: -2 ** 2 is a SyntaxError. Write (-2) ** 2 or -(2 ** 2).
  • 1 < 2 < 3 is (1 < 2) < 3, which is true < 3, which is true. And 3 > 2 > 1 is false.
  • typeof a + b is (typeof a) + b. !a == b is (!a) == b.
  • Postfix i++ returns the old value, and prefix ++i returns the new one. Using both in one expression, such as i = i++ + ++i, is hard to read and should be avoided.
  • The ternary is right associative, which allows chains: a ? b : c ? d : e, but nested ternaries are hard to read.
  • Evaluation order differs from precedence: operands are evaluated left to right even when precedence groups them otherwise, as in f() + g() * h() which calls f, g, h in that order.

Advice: do not memorize the whole table. Know the common rules, and add parentheses when an expression mixes several kinds of operators.

javascript
console.log(2 + 3 * 4, (2 + 3) * 4, 10 - 4 - 3, 2 ** 3 ** 2, (2 ** 3) ** 2);
console.log(true || false && false, (true || false) && false);
console.log(1 < 2 < 3, 3 > 2 > 1, typeof 1 + 2, !0 == 1);

for (const source of ['null ?? "x" || "y"', '(null ?? "x") || "y"', '-2 ** 2', '(-2) ** 2', '-(2 ** 2)']) {
  try {
    console.log(source.padEnd(22), '->', new Function(`return ${source}`)());
  } catch (error) {
    console.log(source.padEnd(22), '->', error.name);
  }
}

let i = 5;
const a = i++;
const b = ++i;
console.log('postfix returns the old value:', a, '| prefix returns the new value:', b, '| i:', i);

let x = 1;
x += x++ + ++x;
console.log('x += x++ + ++x gives', x, '(hard to read, avoid)');

const grade = (score) => (score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F');
console.log([95, 85, 72, 10].map(grade));

const trace = [];
const f = (name, value) => (trace.push(name), value);
const result = f('f', 1) + f('g', 2) * f('h', 3);
console.log(result, trace.join(' then '));

let p, q, r;
p = q = r = 7;
console.log(p, q, r, '| assignment is right associative and returns the value');
console.log(typeof typeof 1, !!'0', +true, -'5', void 0);

Run with Node.js v24.22.1 as js-153.js; two runs gave identical output. Output: 14 20 3 512 64 true false true false number2 true null ?? "x" || "y" -> SyntaxError (null ?? "x") || "y" -> x -2 ** 2 -> SyntaxError (-2) ** 2 -> 4 -(2 ** 2) -> -4 postfix returns the old value: 5 | prefix returns the new value: 7 | i: 7 x += x++ + ++x gives 5 (hard to read, avoid) [ 'A', 'B', 'C', 'F' ] 7 f then g then h 7 7 7 | assignment is right associative and returns the value string true 1 -5 undefined

Key points

  • Precedence ranks operators; associativity breaks ties; parentheses override both.
  • Exponent, assignment, and ternary are right associative; most others are left associative.
  • && is higher than || and ??, but ?? cannot be mixed with them without parentheses.
  • Unary minus directly before ** is a syntax error.
  • Operands are evaluated left to right regardless of precedence; add parentheses for readability.

Common mistakes

  • Relying on memory of the table instead of adding parentheses.
  • Mixing ?? with || or && without parentheses.
  • Expecting 1 < 2 < 3 style chains to behave like in mathematics.
  • Combining ++ in the same expression with other uses of the same variable.

Follow-ups

  • Why is ?? not allowed to mix with || without parentheses?
  • What is the difference between precedence and evaluation order?
  • Why is the exponent operator right associative?

Tips

  • Show two or three examples instead of reciting the table.
  • Mention that parentheses make intent clear.
  • Name the syntax errors that are deliberate.