What is the Nullish Coalescing Operator (??) in JavaScript?
The Nullish Coalescing Operator (??) is used to provide a default value when a variable is null or undefined. It was introduced in ES2020 (ES11). In simple words: If the value is null or undefined, use the fallback value, otherwise, use the original value.
Basic Example
let username = null;
let result = username ?? "Guest";
console.log(result); //GuestNote: ?? returns the right-hand value only if the left-hand value is: null or undefined.
Let's practice with some question below, so that you got the point:
What is the output of below code?
let age;
let finalAge = age ?? 18;
console.log(finalAge);Answer: The output will be 18 as the age is undefined.
What is the output of below code?
let count = 0;
let result = count || 10;
console.log(result); //10Answer: The output will be 10 as the count value is 0 and || (or operator) treat 0 as falsy value so return 10 in the result. But what if you use ?? instead of ||, then the value will be 0 not 10.
What is the output of below code?
let isLoggedIn = false;
let status = isLoggedIn ?? true;
console.log(status);Answer: The output will be false as the value of isLoggedIn is false, not null or undefined.
What is the output of below code?
let name = "";
let finalName = name ?? "Anonymous";
console.log(finalName);Answer: The output will be "" as the value of name is "", not null or undefined.
Combining ?? with Optional Chaining (?.)
let user = {};
let city = user.address?.city ?? "Not Available";
console.log(city);The output of the city will be Not Available as the left side value is undefined.
Lastly, key point to memorize:
The ?? operator is known as Nullish Coalescing Operator.
It is used when we only want to treat null or undefined as falsy value but don't want to treat 0, "", and false as falsy value.