Precedence and Parentheses
You'll learn how operator precedence can surprise you when mixing ?? with && or ||, and when you must use parentheses.
The Core Problem
JavaScript has strict rules about which operators run first (operator precedence). When you try to mix the nullish coalescing operator (??) with logical AND (&&) or logical OR (||) in the same expression without parentheses, JavaScript refuses to guess your intent and throws a syntax error.
This is actually a good thing—it forces you to be explicit.
Why JavaScript Won't Allow It
Consider this invalid expression:
// ❌ SyntaxError!
const result = value1 ?? value2 || value3;
JavaScript could interpret this two different ways:
(value1 ?? value2) || value3value1 ?? (value2 || value3)
Rather than picking one arbitrarily, JavaScript makes you clarify with parentheses.
The Solution: Be Explicit
Always use parentheses when combining ?? with && or ||:
// ✅ Clear intent
const result = (value1 ?? value2) || value3;
// ✅ Also valid
const config = userInput && (userInput.setting ?? defaultSetting);
// ✅ Another example
const name = (firstName ?? lastName) || "Anonymous";
When Parentheses Aren't Needed
You can freely mix ?? with other operators that have clear precedence:
// ✅ These work fine
const sum = (value ?? 0) + 10;
const doubled = (count ?? 1) * 2;
Key Takeaway: When mixing ?? with && or ||, JavaScript requires parentheses to make your intent explicit—this prevents ambiguous code and forces clarity.