JavaScript - Nullish Coalescing Operator
Overview
The nullish coalescing operator (??) was introduced in ECMAScript version 2020. It combines two expressions to return the value of the first expression if it is neither null
nor undefined
or returns the value of the second expression.
Let's take an example to get a clear picture.
let data = null;
let value = data ?? 10;
console.log(value); // 10
Since data
was null, the coalesce operator returned the RHS expression.
let data = 5;
let value = data ?? 10;
console.log(value); // 5
Since data
was neither null
nor undefined
, the coalesce operator returned the LHS expression. Also, the RHS expression was not evaluated to achieve performance gain (commonly described as short-circuiting).
function greet(message){
let prefix = message ?? "Hello";
return `${prefix}, Good Morning!`;
}
console.log(greet()); //Hello, Good Morning!
console.log(greet("Hi")); // Hi, Good Morning!
Here, when we didn't pass the argument message
, its value was undefined. Hence, the value "Hello" got assigned to the variable prefix
.
How did we survive without a coalesce operator to date?
JavaScript users were using the ||
(OR) operator.
You may try replacing the coalesce operator with ||
, and you will see the above code still working as expected.
Then what was the need for a new coalesce operator?
In addition to null
and undefined
, the ||
operator returns the RHS expression for a few more cases that evaluate falsy value. Since the ||
operator expects boolean operands, it will coerce expressions to boolean type. Hence, empty string, 0, boolean false
, NaN, etc. will get evaluated as falsy value.
let data = "";
let value = data || "NA";
console.log(value); // NA
The above code will print the "NA" console, while if you use the nullish coalesce operator, it will not print anything on the console because the output is an empty string.
The typical use case for the nullish coalesce operator is when our applications receive data from outside, and we want to set a default value instead of null
and undefined
. This would avoid numerous null/ undefined checks, making the code more readable and the developers more productive.
There are cases when an empty string is an acceptable value but not null or undefined. The ||
operator falls short here. These real-world scenarios lead to the introduction of the nullish coalesce operator.