The nullish coalescing logical operator('??') in javascript returns its right-hand side operator when its left-hand side operator is either null or undefined.
const result = null ?? "string";
console.log(result); // logs hi foo
Can be also written as:
const result = (a !== null && a !== undefined) ? a : "string";
It is often confused with '||' operator which returns its right-hand side operator when the left-hand side operator is falsy
Here is a list of all the falsy values we have in javascript:
- false (boolean)
- 0
- "", '', ``,
- undefined
- null
- NaN
Problem nullish coalescing operator solves:
The common use case for ?? is to provide a default value for a potentially undefined variable.
Suppose we want to check if a value exists or not, if it exists we want to assign that value or have a default value.
`
const response = {
isSing: true,
isDance: false
};
const isDance = response.isDance || true
`
We want the isDance variable to be whatever value comes from the response for isDance or have a default value of true if it does not exist. Now since response.isDance is false it will always be true. However our intention was to simply check if the isDance variable exists on the response object.
To solve this we can use nullish coalescing operator:
`
const response = {
isSing: true,
isDance: false
};
const isDance = response.isDance ?? true;
console.log(isDance); // false
`
It returns the default value only if the response.isDance results in undefined or null.
`
const response = {
isSing: true,
};
const isDance = response.isDance ?? true;
console.log(isDance); // true
`
Thanks.
Top comments (0)