JavaScript Subtleties: Combining ?? and || Operators
Introduction
If you’re not clear on what the ?? and || operators do, check out our previous post on JavaScript Subtleties: ?? vs ||. In this post, we’ll explore how to combine the ?? and || operators to write more concise and efficient code.
Chaining ?? and ||
You can chain ?? and || operators to provide multiple fallback values:
Copyconst foo = null; const bar = undefined; const baz = 'default'; console.log(foo ?? bar ?? baz); // Output: "default"
In this example, the ?? operator is used to provide a fallback value if foo is null or undefined. If foo is null or undefined, the expression evaluates to bar. If bar is also null or undefined, the expression evaluates to baz.
Using || with ??
You can use || to provide a default value if the expression on the left-hand side of ?? is falsy:
Copyconst foo = 0; const bar = 'default'; console.log((foo ?? bar) || 'fallback'); // Output: "fallback"
In this example, the ?? operator is used to provide a fallback value if foo is null or undefined. The || operator is then used to provide an additional fallback value if the result of the ?? expression is falsy.
Using ?? with || in a conditional statement
You can use ?? and || together in a conditional statement:
Copyconst foo = null; const bar = 'default'; if (foo ?? bar || true) { console.log('Condition is true'); } else { console.log('Condition is false'); }
In this example, the ?? operator is used to provide a fallback value if foo is null or undefined. The || operator is then used to provide an additional condition to evaluate. If foo is null or undefined, the expression evaluates to bar, and the || operator checks if bar is truthy. If bar is falsy, the expression evaluates to true.
Conclusion
Remember to follow the order of operations and use parentheses to clarify the expression when combining ?? and || operators.

