Skip to content
jshacks.dev
Fundamentals

Operator Precedence in JavaScript and the Cases That Bite

Operator precedence decides which operation runs first, and associativity breaks ties. See the table, the bitwise trap and errors added on purpose.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, Node.js and TypeScript logos.

Almost every JavaScript expression you write depends on precedence, and almost none of the time do you think about it. a * b + c does what school taught you. The trouble starts in the few places where the language's order differs from your intuition: a bit test that always returns the wrong thing, a ternary that swallows half a sentence, a -2 ** 2 that refuses to run. Those cases are few enough to learn as a list, and they are the reason style guides tell you to add parentheses. This post gives the table you need, then runs each of the surprising cases with output from Node.js 24 as an ES module, and ends on the habit that makes the table unnecessary. The operators it touches are covered in the post on nullish coalescing and logical OR, the post on bitwise operators and the post on type coercion.

The part of the table you need

The full table has about twenty levels. These are the ones that matter, from tightest to loosest.

LevelOperatorsAssociativity
Grouping( )
Member access, call, new with arguments., [], (), ?.Left
Postfix, prefix, unaryx++, !x, -x, typeof, delete, void, awaitRight
Exponent**Right
Multiplicative*, /, %Left
Additive+, -Left
Shift<<, >>, >>>Left
Relational<, <=, >, >=, in, instanceofLeft
Equality==, !=, ===, !==Left
Bitwise&, then ^, then `\`Left
Logical&&, then `\\ and ??`Left
Conditional? :Right
Assignment=, +=, ??=, and the restRight
Comma,Left

The order for everyday work is arithmetic, then comparison, then equality, then bitwise, then &&, then ||, then the conditional, then assignment. Reading it top to bottom is the order in which an expression is grouped.

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

let a, b, c;
a = b = c = 5;
console.log(a, b, c);
Text
14 20
512 64
3 9
true true false
true false
true true
5 5 5

Multiplication ran before addition. ** grouped from the right, so 2 ** 3 ** 2 is 2 ** 9, which is 512, and not 64. Subtraction grouped from the left. The relational chain 3 > 2 > 1 is (3 > 2) > 1, which is true > 1, which is false, and not a mathematical chain. && bound tighter than ||, so true || false && false is true. And assignment grouped from the right, so the three variables all received 5.

Bitwise operators bind looser than comparison

This is the trap most likely to cost an afternoon. The bitwise operators come after equality in the table, which means x & 1 === 1 is not "the low bit of x equals 1".

JavaScript
const numbers = [4, 5, 6, 7];

console.log(numbers.map((n) => n & 1 === 1));
console.log(numbers.map((n) => (n & 1) === 1));
console.log(numbers.map((n) => n & 1));

const flags = 0b0110;
const READ = 0b0010;

console.log(flags & READ !== 0, (flags & READ) !== 0);
console.log(5 | 2 === 2, (5 | 2) === 2);
Text
[ 0, 1, 0, 1 ]
[ false, true, false, true ]
[ 0, 1, 0, 1 ]
0 true
5 false

The unparenthesized version computed n & (1 === 1), which is n & true, which is n & 1, and so it returned the bit as a number, not a boolean, and 4 and 6 came out as 0, which is falsy, by luck. It looks right on a quick test and fails the moment the result is compared with something. The parenthesized form is the correct test. The flags example shows the same bug with !== 0: flags & (READ !== 0) is flags & true, and the answer is 0, hiding a set flag. Always parenthesize a bitwise expression that is part of a comparison.

Unary minus and exponent

The language refuses an ambiguous case outright. -2 ** 2 could mean (-2) ** 2 or -(2 ** 2), so it is a syntax error, and you must choose.

JavaScript
const sources = ["-2 ** 2", "(-2) ** 2", "-(2 ** 2)", "2 ** -2", "typeof 2 ** 2", "await 2 ** 2"];

for (const source of sources) {
  try {
    console.log(source.padEnd(14), eval(source));
  } catch (error) {
    console.log(source.padEnd(14), error.name);
  }
}

console.log(-(2 ** 2), (-2) ** 2, 2 ** -2);
Text
-2 ** 2        SyntaxError
(-2) ** 2      4
-(2 ** 2)      -4
2 ** -2        0.25
typeof 2 ** 2  SyntaxError
await 2 ** 2   SyntaxError
-4 4 0.25

The first form fails to parse, and the parenthesized versions give 4 and -4. A negative exponent is fine, because the minus belongs to the exponent. typeof 2 ** 2 fails for the same reason as the first: a unary operator directly before ** is ambiguous. The await case, in a context where it is not an operator, is a different error and not worth remembering.

Mixing nullish coalescing with logical operators

The same refusal applies to ?? next to || or &&. The specification has no precedence between them, so the combination needs parentheses.

JavaScript
const attempts = [
  "null ?? 'a' || 'b'",
  "(null ?? 'a') || 'b'",
  "null ?? ('a' || 'b')",
  "0 || null ?? 'x'",
  "null ?? undefined ?? 'last'",
];

for (const source of attempts) {
  try {
    console.log(source.padEnd(28), eval(source));
  } catch (error) {
    console.log(source.padEnd(28), error.name);
  }
}
Text
null ?? 'a' || 'b'           SyntaxError
(null ?? 'a') || 'b'         a
null ?? ('a' || 'b')         a
0 || null ?? 'x'             SyntaxError
null ?? undefined ?? 'last'  last

Unparenthesized mixes are syntax errors, and either grouping works when stated. Chains of ?? alone are fine and group from the left. The rule was added because two plausible readings existed, and a language that guesses would have caused the bugs the rule prevents.

The conditional operator swallows the right side

The conditional ? : is looser than almost everything, so it takes the whole expression to its left as the condition, and the whole of each branch to its right.

JavaScript
const count = 3;
const price = 10;

console.log("total: " + count * price > 25 ? "big" : "small");
console.log("total: " + (count * price > 25 ? "big" : "small"));

const label = count > 5 ? "many" : count > 1 ? "some" : "few";
console.log(label);

const age = 20;
console.log(age >= 18 && age < 65 ? "adult" : "other");
console.log(age > 18 ? "a" : "b" + "c");
Text
small
total: big
some
adult
a

The first line printed small and none of the text that was meant to come before it. The condition was the whole expression "total: " + count * price > 25, which compares the string "total: 30" with 25, converts the string to NaN and is therefore false, so the conditional produced only its false branch. Wrapping the conditional in parentheses fixes it, as the second line shows. Chained conditionals group from the right, so the second ? belongs to the false branch of the first. And the last line shows the branch expression extending as far as it can: "b" + "c" is the false branch, whole.

Addition, concatenation and mixed types

Both + and - group from the left, so the type of the running result changes as the expression is evaluated.

JavaScript
console.log(1 + 2 + "3", "1" + 2 + 3, 1 + +"2" + 3);
console.log("5" - 2 + "1", "5" + 2 - 1);
console.log(1 + 2 * 3 + "4", 1 + 2 * "3");
console.log([] + 1 + 2, {} + 1);
console.log(+"3" + +"4", -"3" - -"4");
Text
33 123 6
31 51
74 7
12 [object Object]1
7 1

Evaluation goes left to right, so the first sum is added as numbers and then concatenated, and the second is concatenated from the start. A unary plus converts the string before the addition happens. These results follow from the coercion rules applied in precedence order, and they are the reason to use template literals for building strings.

new, member access and calls

new Foo() with arguments binds tighter than a member access on its result, and new Foo without arguments binds looser than the call, which changes what new Foo.bar() means.

JavaScript
class Greeter {
  constructor() {
    this.kind = "instance";
  }
  hello() {
    return "hi from " + this.kind;
  }
}

console.log(new Greeter().hello());

const ns = {
  Greeter,
  make() {
    return new Greeter();
  },
};

console.log(new ns.Greeter().hello());
console.log(typeof new ns.Greeter, typeof ns.make().hello);

try {
  console.log(new Greeter.hello());
} catch (error) {
  console.log(error.name);
}
Text
hi from instance
hi from instance
object function
TypeError

new Greeter().hello() creates the object first, then calls the method, because new with arguments has higher precedence than the member access after it. new ns.Greeter() constructs through the namespace. And new Greeter.hello() tries to construct the method itself, which is not a constructor. The rule of thumb is to always write the parentheses after new X, and to wrap the construction if you chain from it.

Testing an expression you are unsure about

When you cannot tell how an expression groups, do not trust memory. Evaluate the two parenthesized readings and compare them, and print the type of the result as well as the value. A one-line check in a scratch file is faster than a trip to the table, and a test with the comparison in it documents the decision. For a bitwise condition, for example, assert that (flags & MASK) !== 0 is true for a set bit and false for a clear one, so a later edit that drops the parentheses fails at once.

A habit that replaces the table

Nobody keeps the table in their head, and the code should not require it. Three habits cover almost everything. Parenthesize every bitwise expression and every mix of && with ||. Parenthesize the condition and each branch of a conditional that is part of a larger expression. And use a formatter: Prettier keeps parentheses that clarify and removes those that do not, so the code that remains is exactly the code where precedence matters to a reader.

ESLint rules no-mixed-operators and no-extra-parens support the habit from both sides, flagging the missing and the redundant ones.

Where the table stops

Precedence says how an expression is grouped. It does not say in what order the operands are evaluated: JavaScript evaluates operands left to right, which is a separate guarantee. In f() + g() * h() the multiplication binds first, yet f is still called first, then g, then h. That separation matters when operands have side effects, and it is the reason i++ + i++ is well defined in JavaScript, where it is undefined in some other languages.

The grammar is defined in the specification under expressions, and MDN keeps the full operator precedence table with associativity for every operator.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.