The Nullish Coalescing Operator in JavaScript
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is nullish (null
or undefined
), and otherwise returns its left-hand side operand.
This can be seen as a special case of the logical OR
(||
) operator, which returns the right-hand side operand if the left operand is any falsy value, not only nullish.
Remember that a nullish value and a falsy value are different concepts. While null
, undefined
, 0
, ''
, false
, and NaN
are considered falsy values, only null
and undefined
are considered nullish values.
Check the following code snippet:
Usage with the optional chaining operator (?.)
The nullish coalescing operator treats undefined
and null
as specific values and so does the optional chaining operator (?.
) which is useful to access a property of an object which may be null or undefined.
Check the following code snippet:
Check browser compatibility: https://caniuse.com/mdn-javascript_operators_nullish_coalescing
About the author:
Miguel Munoz is a Principal Software Engineer here at Version 1.