Table of contents
Introduction
Nullish coalescing operator (??) was introduced in the ECMAScript 2020 specification, which can be used to replace the logical OR operator for setting the default values.
Syntax:
left Operand ?? right Operand
The left operand is first checked if it is not null or undefined, then returns the left operand without evaluating the right operand otherwise returns the right operand.
Before the Nullish coalescing operator (??) logical OR operator was used, let's check the OR operator and analyze both operators.
Overview
The falsy value is something that evaluates to FALSE, for instance when checking a variable. There are only six falsy values in JavaScript:
null
undefined
' ';
NaN
0
false
The syntax for OR Operator:
left Operand || right Operand
The Logical OR Operator (||) checks the left operand if it is not any of the above falsy values then returns the left operand without evaluating the right operand.
Otherwise returns Right Operand.
console.log(4 || 5 ); //4
console.log(null || "Hello") //Hello
console.log(undefined || null) //null
In the above code snippet, In the first line, it first checks for the value in the left operand and it is a truthy value, so it short circuits and console logs the number 4 without even evaluating the right operand.
In the second line, it checks the left operand is a falsy value and then logs the right operand.
In the third line, it checks the left operand is a falsy value and logs the right operand even if it is a falsy value.
This Logical OR Operator (||) has some limitations, Let's take an example of it.
let Books = 0;
function getBooks(){
let NoOfBook = Books || 4;
console.log(NoOfBook); //4
}
getBooks();
In this example, the OR operator checks the left operand as falsy values and logs 4, even though Books is 0.
We may want to use the default value only when the variable is null/undefined
. That is when the value is really unknown/not set.
The nullish coalescing operator resolves this problem as it has only two falsy values: null and undefined.
let Books = 0;
function getBooks(){
let NoOfBook = Books ?? 4;
console.log(NoOfBook); //0
}
getBooks();
The nullish coalescing operator checks the left operand i.e. Books value 0, so it is the truthy value in the operator, short circuits, and the NoOfBook value is 0.
Conclusion
The nullish coalescing operator can be used to set the default values for null or undefined values.