Sub topic 10
Precedence Rules and Required Parentheses
This chapter assumes you know how ?? picks a right-hand value only when the left side is null or undefined, and how || and && short-circuit. It also assumes you know that operator precedence decides how JavaScript groups an expression that has no parentheses. Here you will learn three things: which mixes of ?? with other operators are illegal, how ?? groups with arithmetic, comparison and the ternary operator, and where a missing pair of parentheses silently changes the result.
The Rule: `??` Will Not Mix with `||` or `&&`
JavaScript refuses to parse an expression where ?? sits directly next to || or && without parentheses. The error does not depend on the values involved. It is a grammar rule, so the engine rejects the code before running a single line of it.
const a = null;
const b = 0;
// Each of these lines is a SyntaxError if uncommented:
// const r1 = a || b ?? 5;
// const r2 = a ?? b || 5;
// const r3 = a && b ?? 5;
// const r4 = a ?? b && 5;
const good1 = (a || b) ?? 5; // (null || 0) -> 0, then 0 ?? 5 -> 0
const good2 = a ?? (b || 5); // null ?? (0 || 5) -> 5
const good3 = (a && b) ?? 5; // (null && 0) -> null, then null ?? 5 -> 5
console.log(good1, good2, good3); // 0 5 5good1 and good2 use the same three operands and the same two operators, yet they produce different results. That difference is the reason the rule exists. When the TC39 committee added ?? in ES2020, they could have given it a fixed precedence relative to ||. They decided instead that a reader cannot reliably guess the intended grouping, so the language makes you write it.
Why the error breaks the whole file
A SyntaxError is raised while the engine parses the source, before any code runs. A try...catch in the same script cannot catch it, and none of the file's other statements run either. In a browser, one bad line in a <script> stops every function in that script. In Node.js, the module fails to load.
To watch the parser reject expressions without crashing your program, compile them at runtime with new Function. This parses its string argument as a separate piece of code, so the error surfaces as a normal exception:
const candidates = [
"a || b ?? c",
"a ?? b || c",
"a && b ?? c",
"a ?? b && c",
"(a || b) ?? c",
"a ?? (b && c)",
"a ?? b ?? c",
"!a ?? b",
"a ?? b | c",
];
for (const src of candidates) {
try {
new Function("a", "b", "c", `return ${src};`);
console.log("parses ", src);
} catch (err) {
console.log("rejected ", src, "->", err.name);
}
}Running this in Node.js 14 or later prints rejected for the first four lines and parses for the rest. Different engines word the message differently. V8 (Chrome, Node.js) usually reports an unexpected token, while Firefox names the problem directly. The error type is always SyntaxError.
What `??` Groups With
In the specification's grammar, each operand of ?? must be an expression at the bitwise-OR level or tighter. In practice, everything that binds more tightly than && can appear on either side of ?? without parentheses. That covers bitwise operators, equality, comparison, arithmetic, unary operators, member access, calls and ?.. Anything that binds more loosely than ??, such as the ternary operator, assignment, arrow functions and the comma, takes the whole ?? expression as one piece.
The table shows how common unparenthesized expressions are grouped.
| You write | JavaScript reads it as | Legal? | Column | Column |
|---|---|---|---|---|
| `a ?? b ?? c` | `(a ?? b) ?? c` | Yes | ||
| `a?.b ?? c` | `(a?.b) ?? c` | Yes | ||
| `a ?? b + 1` | `a ?? (b + 1)` | Yes | ||
| `"Hi " + name ?? "guest"` | `("Hi " + name) ?? "guest"` | Yes | ||
| `a ?? b > 0` | `a ?? (b > 0)` | Yes | ||
| `!a ?? b` | `(!a) ?? b` | Yes | ||
| `a ?? b ? x : y` | `(a ?? b) ? x : y` | Yes | ||
| `x = a ?? b` | `x = (a ?? b)` | Yes | ||
| `a \ | \ | b ?? c` | none | SyntaxError |
| `a ?? b && c` | none | SyntaxError |
Chaining ?? with itself is fine. It groups left to right, and because each step only replaces nullish values, (a ?? b) ?? c and a ?? (b ?? c) always produce the same result. The common pattern of reading a nested value with ?. and then supplying a default with ?? is also legal without parentheses, because ?. binds as tightly as ordinary property access.
Legal but Wrong: Silent Grouping Bugs
The SyntaxError cases are the easy ones because the engine tells you immediately. The table also contains expressions that parse fine and quietly compute something you did not mean. All of them come from ?? binding more loosely than arithmetic and comparison.
Arithmetic on the right
const order = { quantity: undefined, extra: 2 };
const wrong = order.quantity ?? 1 + order.extra; // undefined ?? (1 + 2) -> 3
const right = (order.quantity ?? 1) + order.extra; // (undefined ?? 1) + 2 -> 3
const order2 = { quantity: 5, extra: 2 };
console.log(order2.quantity ?? 1 + order2.extra); // 5 (extra is ignored)
console.log((order2.quantity ?? 1) + order2.extra); // 7With a missing quantity, both versions return 3, so a test that only covers the missing case passes. Once a real quantity arrives, the unparenthesized version drops the addition entirely. When the default is meant to feed a larger calculation, wrap the ?? expression in parentheses.
String concatenation on the left
const name = undefined;
console.log("Hello, " + name ?? "guest"); // "Hello, undefined"
console.log("Hello, " + (name ?? "guest")); // "Hello, guest"+ runs first, so the left operand of ?? is the string "Hello, undefined". A string is never nullish, so the default can never apply. A template literal avoids this because the placeholder sets its own boundary: ` Hello, ${name ?? "guest"} `.
Comparisons
const stats = { count: 3 };
if (stats.count ?? 0 > 5) {
console.log("many items"); // runs: 3 ?? (0 > 5) is 3, which is truthy
}
if ((stats.count ?? 0) > 5) {
console.log("many items"); // does not run
}The first condition evaluates 0 > 5 to false and only uses it if count is nullish. Otherwise it tests count for truthiness, which is a different question. Equality behaves the same way: a ?? b === c means a ?? (b === c).
Unary operators
!a ?? b is legal, but !a always produces a boolean, and a boolean is never nullish. The right side never runs. If you meant "negate the value or its default", write !(a ?? b). The same applies to typeof a ?? "none": typeof always returns a string, so the default is dead code.
The ternary operator
The ternary operator binds more loosely than ??, so a ?? b ? x : y tests the result of a ?? b. This is usually what you want. The surprise goes the other way: putting ?? inside a branch needs no parentheses, but putting a ternary in the right operand of ?? does.
const theme = null;
const prefersDark = true;
const t1 = theme ?? (prefersDark ? "dark" : "light"); // "dark"
const t2 = theme ?? prefersDark ? "dark" : "light"; // (null ?? true) ? ... -> "dark"
const theme2 = "solarized";
console.log(theme2 ?? (prefersDark ? "dark" : "light")); // "solarized"
console.log(theme2 ?? prefersDark ? "dark" : "light"); // "dark" (theme2 is lost)Choosing Where the Parentheses Go
When you hit the mixing SyntaxError, do not add parentheses until the error goes away. First decide what each operator is for:
- Name the value that might be missing. That value belongs on the left of
??. - Decide whether the
||or&&part produces that value or the fallback. - If it produces the value, group it on the left:
(a || b) ?? c. If it produces the fallback, group it on the right:a ?? (b || c).
For example, user.nickname || user.fullName ?? "Anonymous" is rejected. If an empty nickname should fall through to the full name, the || part chooses the value, so you write (user.nickname || user.fullName) ?? "Anonymous". If you only care about missing data, you probably wanted ?? throughout: user.nickname ?? user.fullName ?? "Anonymous".
The compound assignment ??=, covered in its own chapter, has none of these problems. It binds like =, so x ??= a + b means x ??= (a + b), and x ??= a || b is legal because the right side is a complete expression.
Exercise
Given const limit = 10; const used = undefined;, what does limit - used ?? 0 evaluate to, and why? Rewrite it so a missing used counts as 0.
Show answer
It evaluates to NaN. Subtraction binds more tightly than ??, so the expression is (limit - used) ?? 0, which is NaN ?? 0. NaN is not nullish, so it is kept. The fix is limit - (used ?? 0), which gives 10.
Exercise
Which of these lines cause a SyntaxError? (1) a ?? b ?? c (2) a && b ?? c (3) (a && b) ?? c (4) a?.x ?? b || c (5) a ?? b === c
Show answer
Lines 2 and 4. Line 2 mixes && with ?? without parentheses. Line 4 mixes ?? with ||; the ?. is irrelevant. Line 1 is chained ??, which is allowed. Line 3 is parenthesized. Line 5 parses as a ?? (b === c), which is legal, though possibly not what was intended.
Exercise
A teammate writes const label = "Items: " + cart?.count ?? 0; and it shows "Items: undefined" when the cart is null. Explain the bug and give two fixes.
Show answer
+ runs before ??, so the left operand of ?? is the string "Items: undefined", which is never nullish, and the default never applies. Fix it with parentheses, "Items: " + (cart?.count ?? 0), or with a template literal, ` Items: ${cart?.count ?? 0} `.