Differences between ?? and || in JavaScript
When working with JavaScript, it’s important to understand the differences between the nullish coalescing operator (??) and the logical OR operator (||).
First, let’s discuss the nullish coalescing operator (??). This operator is used to provide a default value when a variable is null or undefined. For example, if we have a variable foo
that may be null or undefined, we can use the ?? operator to assign a default value like this:
const result = foo ?? 'default value';
In this case, if foo
is null or undefined, the value of result
will be ‘default value’.
On the other hand, the logical OR operator (||) is used to return the first truthy value in a set of values. This means that if the first operand is falsy, the second operand will be returned. For example:
const result = foo || 'default value';
In this case, if foo
is null, undefined, false, 0, or an empty string, the value of result
will be ‘default value’.
It’s important to note that the ?? operator only checks for nullish values (null or undefined), while the || operator checks for any falsy value. This distinction is crucial when choosing which operator to use in your JavaScript code.
In conclusion, while both ?? and || operators provide default values in JavaScript, the nullish coalescing operator (??) is more specific in checking for null or undefined values only, whereas the logical OR operator (||) checks for any falsy value.
?? For null and undefined
I didn't even know the "||" operator was usable in that context. I guess it makes sense, but I've never considered it or seen it done.