What is Nullish coalescing operator (??) in javascript?
It is an operator which handles the undefined and null values. It is denoted by ??
Expression1 ?? Expression2
Nullish coalescing operator first checks Expression1.
- If Expression1 is undefined or null it will return Expression2.
const nullishVariable = null;
const randomNumber = 89;
const result = nullishVariable ?? randomNumber;
console.log(result); // It will print 89
Explanation-Here Expression1 is nullishVariable which is null so it will return the randomNumber which is Expression2.
- if Expression1 is not undefined or null then it will return Expression1 itself.
const stringVariable = "Orange";
const randomNumber = 89;
const result = stringVariable ?? randomNumber;
console.log(result); // it will return orange
Explanation- Here Expression1 is stringVariable and it is not null or undefined so it will return Expression1 without checking Expression2.
- if Expression1 and Expression2h both are undefined or null. It will return Expression2.
const nullish = null;
const undefinedVariable = undefined;
const result = nullish ?? undefinedVariable;
console.log(result); // it will return undefined
Explanation- Here first Expression1 is null so it will return the second Expression without checking it which is undefined.
As we go through the above three cases but did you think about why we should use this operator in javascript?
To set the default value if we don't receive the value of any variable.
const result= text ?? "Hello"; console.log(result); // Hello as text is undefined
Conclusion- Nullish coalescing operator (??) is used for handling undefined and null in javascript. In other words sometimes we don't get the value from API's or Object or variable is not defined etc then we set the default value so that we don't get the unexpected behavior of the code.