Let's take a look at the nullish coalescing operator (??
) in JavaScript. At the time of writing, it works in the latest versions of Chrome, Firefox, and Edge. It's still a bit shaky for cross-browser stability, though, so please think twice about using it in a production environment.
Before we begin, a little bit of context...
My friend Stuart Ashworth and I were discussing the ternary operator in PHP. Interestingly, it does something that the ternary operator in JavaScript does not. As explained in the PHP docs:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3
returnsexpr1
ifexpr1
evaluates totrue
, andexpr3
otherwise.
In JavaScript, this is just like short-circuit evaluation with the logical OR (||
) operator. But Stuart mentioned the nullish coalescing operator, and we wondered what the difference is.
The nullish coalescing operator (??
) only returns its right-hand side operand when its left-hand side operand is null
or undefined
.
The logical OR operator (||
), on the other hand, returns its right-hand side operand if its left-hand side operand is falsy. This also includes the following values (borrowed from the MDN Web Docs):
false
0
-0
0n
""
NaN
Practically speaking, I might use the nullish coalescing operator to assign default values once it's better supported. It's a bit stricter and more specific, which is a good thing for me. It makes my code less error-prone.
The use case for this would be if I didn't want to allow null
or undefined
, but I did want to allow some falsy values. For example...
function someFunction (someParameter) {
// This wouldn't allow ANY falsy value
someParameter = someParameter || "someString";
// This would allow any value EXCEPT null and undefined
someParameter = someParameter ?? "someString";
}
You can follow the latest browser support information if you're interested.