You may have seen OR operator ||
used commonly to handle default values. But, there is also the less known nullish coalescing operator ??
that can also help with handling default values. Though similar, there are some key deferences between the two.
The OR operator ||
returns the first truthy value in a series of expressions. If all expressions evaluate to falsy values, the final expression is returned. This means that the OR operator will return the second expression if the first expression is falsy, even if the second expression is also falsy.
For example, consider the following code:
const x = 0 || false;
console.log(x); // false
In this case, the OR operator returns the second expression false
because the first expression 0
is falsy.
The nullish coalescing operator (??) returns the first defined value in a series of expressions. If the first expression is null or undefined, the second expression is returned. This means that the nullish coalescing operator will only return the second expression if the first expression is null or undefined.
For example, consider the following code:
const y = null ?? 'default';
console.log(y); // 'default'
In this case, the nullish coalescing operator returns the second expression default
because the first expression null
is nullish.
One of the key differences between these two operators is how they handle falsy values. The OR operator considers any falsy value (e.g. 0, '', false) to be equivalent to false, while the nullish coalescing operator only considers null
and undefined
to be nullish.
For example, consider the following code:
const z = '' || 'default';
console.log(z); // 'default'
const w = '' ?? 'default';
console.log(w); // ''
In this case, the OR operator returns the second expression 'default'
because the first expression ''
is falsy, while the nullish coalescing operator returns the first expression ''
because it is not nullish.
In general, developers should use the nullish coalescing operator when they want to specifically check for null or undefined values, and the OR operator when they want to handle any falsy value. However, it's important to consider the context in which these operators are being used and choose the one for your specific use case.
Top comments (0)