In this post, we will understand how the nullish coalescing operator works in JavaScript. The nullish coalescing operator (??) is a logical operator in JavaScript that is used to check if a value is null
or undefined
. If the value is either null
or undefined
, the operator returns the value on the right side of the operator, otherwise, it returns the value on the left side.
Let's understand this in detail with an example:
const foo = null;
const bar = 0;
console.log(foo ?? 'default value'); // Output: 'default value'
console.log(bar ?? 'default value'); // Output: 0
In the first example, the value of foo
is null
, so the ?? operator returns the default value 'default value'
. In the second example, the value of bar
is 0
, which is a valid value, so the ?? operator returns the value of bar
, which is 0
.
The nullish coalescing operator is similar to the logical OR operator (||
), but it only returns the right-side value if the left-side value is null
or undefined
, whereas the logical OR operator returns the right-side value if the left-side value is falsy (i.e., null
, undefined
, 0
, ''
, false
).
Here is an example that demonstrates the difference between the nullish coalescing operator and the logical OR operator:
const foo = null;
const bar = 0;
console.log(foo ?? 'default value'); // Output: 'default value'
console.log(foo || 'default value'); // Output: 'default value'
console.log(bar ?? 'default value'); // Output: 0
console.log(bar || 'default value'); // Output: 0
In both examples, the nullish coalescing operator and the logical OR operator return the default value 'default value'
when the value of foo
is null
, but the logical OR operator also returns the default value when the value of bar
is 0
, which is considered a falsy value. The nullish coalescing operator, on the other hand, only returns the default value when the value is null
or undefined
.
I hope you found this tutorial useful. In case you've any queries or feedback, feel free to drop a note in comments.