Operator Precedence & Associativity

The rules that decide who binds first -- and why parentheses beat memorising all of them.

Syntaxgrouping () > ** (right) > * / % > + - > comparisons > && > || > ??

Precedence decides which operator grabs its operands first; associativity breaks ties between operators of equal precedence.

The handful worth internalising

  1. Member access . ?. and calls () bind tightest.
  2. ** is right-associative and outranks unary minus, so -2 ** 2 is a syntax error on purpose -- write -(2 ** 2) or (-2) ** 2.
  3. * / % beat + -.
  4. Comparisons beat &&, which beats ||, which beats ?? (they cannot even mix without parens).
  5. Assignment and the comma operator are near the bottom.
2 + 3 * 4        // 14, not 20
a || b && c      // a || (b && c)
!x === y         // (!x) === y

The 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

Try it yourself
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.

Example Β· js
console.log(2 + 3 * 4);    // 14 – * before +
console.log((2 + 3) * 4); // 20 – parens override

Comparison and logical precedence

AND binds tighter than OR; the first expression evaluates b&&c first, then ORs with a.

Example Β· js
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); // false

Assignment vs equality in a condition

Shows that assignment = has lower precedence than ===; extra parens make the intent explicit.

Example Β· js
let x = 0;
// if (x = 5) { ... }  // assignment in condition – always truthy!
if ((x = 5) === 5) {
  console.log("x is", x); // "x is 5"
}

Discussion

  • Be the first to comment on this lesson.
Operator Precedence & Associativity β€” JavaScript | SoundsCode