How to Use Nullish Coalescing With Logical AND/OR Operators in JavaScript?

You can use the nullish coalescing operator (??) and the logical AND (&&) or OR (||) operators together in the same expression. However, you must use parentheses to disambiguate the order in which the operators are evaluated; otherwise a SyntaxError would be thrown. For example:

// Edge, Chrome, Safari, Opera
// Uncaught SyntaxError: Unexpected token '??'
null || false ?? 'foo';
// Firefox
// Uncaught SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
null || undefined ?? 'foo';

This happens because nullish coalescing operator has a lower order of precedence than logical AND/OR operators, which may lead to unexpected results. This is especially true, for example, if you combine these operators in a more complex expression where the nullish coalescing operator might be evaluated last.

For this reason, JavaScript does not allow to combine these operators together directly. Instead, you must use parentheses to explicitly indicate the precedence (as parentheses/grouping has the highest order of precedence). For example:

(null || false) ?? 'foo'; // false
(null || undefined) ?? 'foo'; // 'foo'
(true || false) ?? 'foo'; // true

Although, parentheses/grouping has the highest order of precedence, in some cases it may not be evaluated first. For example, one such case is when short-circuiting (i.e. conditionally evaluating an expression):

null && (undefined ?? 'foo'); // null
1 || (undefined ?? 'foo'); // 1

In the first example, the first part of the expression is falsy, therefore, the second part of the expression (i.e. (undefined ?? 'foo')) is never evaluated (even if it is in parentheses). Similarly, in the second example, the second part of the expression is never evaluated because the first part evaluates to true.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.