In the realm of JavaScript, there exists a powerful operator known as the nullish coalescing operator, represented by ??
.
You may be familiar with the use of the ||
operator to set a default value when a variable is null or undefined, like this:
const myColor = color || 'red';
However, the nullish coalescing operator is here to take the place of ||
in scenarios like these:
const myColor = color ?? 'red';
But what makes this operator particularly useful?
The ||
operator can introduce hidden bugs when used to provide fallback values since it considers values as falsy. On the other hand, the ??
operator specifically handles nullish values, giving it its distinct name.
To clarify, when using ||
, the second operand is evaluated if the first operand is either undefined
, null
, false
, 0
, NaN
or ''
. However, ??
narrows down this list to only undefined
and null
.
By understanding the nuances of nullish coalescing, you can enhance your coding practices and avoid potential pitfalls associated with using the ||
operator.