Sub topic 12
Precedence Rules and Why ?? Needs Parentheses
This chapter assumes you already know how &&, || and ?? choose and return an operand, and how short-circuit evaluation skips the right-hand side. It also assumes you can read console.log output and write small functions. Here you will learn how JavaScript groups an expression that has several of these operators, which groupings are a SyntaxError, and when you should add parentheses even though the language does not require them.
The Precedence Levels That Matter Here
Precedence decides which operator binds its operands first when you write no parentheses. A higher level binds tighter. The table lists only the operators that usually appear in truthiness-related code.
| Level (higher binds tighter) | Operators | Example grouping | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|
| Unary | `!`, `typeof` | `!a == b` is `(!a) == b` | ||||||
| Relational | `<`, `>`, `<=`, `>=`, `in`, `instanceof` | `!k in o` is `(!k) in o` | ||||||
| Equality | `==`, `!=`, `===`, `!==` | `a === b && c` is `(a === b) && c` | ||||||
| Logical AND | `&&` | `a | b && c` is `a | (b && c)` | ||||
| Logical OR and nullish | ` | `, `??` | cannot be mixed without parentheses | |||||
| Conditional | `? :` | `a ?? b ? x : y` is `(a ?? b) ? x : y` | ||||||
| Assignment | `=`, ` | =`, `&&=`, `??=` | `x ??= a | b` is `x ??= (a | b)` |
|| and ?? sit at the same level, and that placement causes the special rule this chapter is named after. First, look at how && and || combine.
&& Binds Tighter Than ||
a || b && c is parsed as a || (b && c). This works like multiplication binding tighter than addition. Short-circuiting follows the grouping. If a is truthy, the whole b && c group is skipped.
function log(name, value) {
console.log(`evaluated ${name}`);
return value;
}
const r1 = log("a", "A") || log("b", "B") && log("c", "C");
console.log(r1);
// evaluated a
// A
const r2 = log("a", "") || log("b", "B") && log("c", "C");
console.log(r2);
// evaluated a
// evaluated b
// evaluated c
// CIn r1, "A" is truthy, so || returns it and never looks at its right operand, which is the entire && group. In r2, "" is falsy, so || evaluates b && c. "B" is truthy, so && returns "C".
The following diagram shows the tree the parser builds.
The grouping is correct, but readers often misjudge it. If you write a || b && c, consider writing a || (b && c) so the reader does not have to recall the table.
Why ?? Cannot Be Mixed with || or &&
When TC39 (the committee that standardizes JavaScript) added ??, it had to choose how a ?? b || c should group. Each choice would have surprised someone. Some developers read ?? as a kind of || and expect left-to-right grouping. Others expect ?? to behave like a lower-precedence fallback. The committee chose to make the mix illegal. Any expression that puts ?? next to || or && without parentheses is a SyntaxError.
The following script feeds several expressions to the parser through new Function, so the error can be caught and printed:
const sources = [
'null || undefined ?? "default"',
'null ?? undefined || "default"',
'true && null ?? "default"',
'(null || undefined) ?? "default"',
'null ?? (undefined || "default")',
'null ?? undefined ?? "default"',
];
for (const src of sources) {
try {
const result = new Function(`return ${src};`)();
console.log(`${src} -> ${result}`);
} catch (e) {
console.log(`${src} -> ${e.name}`);
}
}
// null || undefined ?? "default" -> SyntaxError
// null ?? undefined || "default" -> SyntaxError
// true && null ?? "default" -> SyntaxError
// (null || undefined) ?? "default" -> default
// null ?? (undefined || "default") -> default
// null ?? undefined ?? "default" -> defaultThe output shows three rules:
- Mixing
??with||or&&fails in either order. - Parentheses on either side make the expression legal.
- A chain of only
??operators is fine. It groups left to right,(a ?? b) ?? c, and returns the first operand that is notnullorundefined.
Parentheses Change the Result
Because the language forces you to choose a grouping, you need to know which one you mean. The two groupings can return different values for the same inputs.
const a = 0;
const b = null;
const c = 5;
console.log(a ?? (b || c)); // 0
console.log((a ?? b) || c); // 5In the first line, a is 0, which is not nullish, so ?? returns 0 and skips the parenthesized group. In the second line, a ?? b also gives 0, but then 0 || 5 treats 0 as falsy and returns 5. If 0 is a valid value, such as a volume setting, only the first form keeps it.
To decide which grouping you need, ask what each fallback is meant to catch:
- Use
x ?? (y || z)whenxshould win unless it is missing, andyshould be replaced only when it is falsy. - Use
(x || y) ?? zwhen any falsyxshould give way toy, andzis the last resort only ifyis missing too. - Use
(cond && value) ?? fallbackwhenvalueapplies only ifcondholds. Remember that a falsycondis returned as it is. Afalsepasses straight through??, because??replaces onlynullandundefined.
The following example shows that last point:
const isAdmin = false;
const adminName = "root";
console.log((isAdmin && adminName) ?? "guest"); // false
console.log((isAdmin && adminName) || "guest"); // guestGotchas with Other Operators
! binds tighter than in and ==
! is a unary operator, so it applies before relational and equality operators.
const obj = { id: 1 };
console.log(!"name" in obj); // false
console.log(!("name" in obj)); // true!"name" in obj becomes false in obj. The in operator converts false to the key "false", which obj does not have, so the result is false. Only the parenthesized version asks the question you meant.
Comparisons bind tighter than ??
?? has low precedence, so arithmetic and comparisons on its right are grouped first.
function passed(score) {
return score ?? 0 >= 50;
}
console.log(passed(null)); // false
console.log(passed(30)); // 30
console.log(passed(80)); // 80
function passedFixed(score) {
return (score ?? 0) >= 50;
}
console.log(passedFixed(null)); // false
console.log(passedFixed(30)); // false
console.log(passedFixed(80)); // trueThe first version parses as score ?? (0 >= 50). It returns the raw score whenever one exists, and 30 is truthy, so an if (passed(30)) check would wrongly succeed. The same trap applies to ||, for example count || 0 + 1.
The conditional operator binds looser
? : sits below ??, || and &&, so the whole logical expression to its left becomes the condition.
const user = null;
const guest = { name: "Guest" };
const greeting = user ?? guest ? "Hello" : "Who are you?";
console.log(greeting); // HelloThis parses as (user ?? guest) ? "Hello" : "Who are you?". On the other side of the colon, flag ? a : b ?? c means flag ? a : (b ?? c). Both groupings are legal, but parentheses make the intent clear.
Logical assignment takes the whole right side
??=, ||= and &&= are assignment operators, so their right side is a complete expression. opts.name ??= input || "anon" is legal and means opts.name ??= (input || "anon"). This does not count as mixing ?? with ||, because ??= is a different token.
A Practical Policy
The table tells you how JavaScript parses an expression. It does not tell the next reader what you meant. Many teams use these rules:
- Always parenthesize when
&&and||appear together. - Wrap the left side of
??in parentheses when it contains arithmetic or a comparison, and do the same for the right side. - Never rely on
!applying to a whole comparison. Write!(a in b)or!(a === b). - Turn on ESLint's
no-mixed-operatorsrule to flag unparenthesized mixes automatically.
Code formatters such as Prettier keep the parentheses you write, so explicit grouping is not removed when the code is reformatted.
Exercise
For each line, give the printed value or say that it is a SyntaxError: (1) console.log("" || null && "x"); (2) console.log(0 ?? null || 7); (3) console.log((0 ?? null) || 7); (4) console.log(undefined ?? null ?? 0);
Show answer
(1) null. && groups first: null && "x" is null, then "" || null returns null. (2) SyntaxError, because ?? is mixed with || without parentheses, and the whole script fails to parse. (3) 7. 0 ?? null is 0, then 0 || 7 returns 7. (4) 0. A pure ?? chain is legal and returns the first operand that is not nullish.
Exercise
A function returns limit ?? 10 * 2 and callers pass either a number or undefined. A teammate says it returns 20 for undefined and the given limit otherwise. Is that right? Now consider enabled ?? true && hasAccess. Is it legal, and if not, how would you fix it so that a missing enabled defaults to true before the access check?
Show answer
The first claim is right. binds tighter than ??, so the expression is limit ?? (10 2), which gives 20 for undefined and limit otherwise. The second expression is a SyntaxError because ?? and && are mixed without parentheses. Write (enabled ?? true) && hasAccess, so the default is applied first and the result is then combined with hasAccess.
Exercise
Why does !"id" in { id: 1 } evaluate to false even though the object has an id property?
Show answer
! has higher precedence than in, so the expression is (!"id") in { id: 1 }. !"id" is false, and in converts it to the key "false". The object has no "false" property, so the result is false. Write !("id" in obj) to negate the membership test.