Nullish coalescing operator

The “Nullish coalescing operator” is the recently added in JavaScript. It treats null and undefined in same way and returns first defined value.
Example:
The result of a ?? b is,
if a is defined then returns a otherwise returns b.
Before Nullish coalescing operator introduced we were checking the expression is null or undefined using below way,
var a = { name: “abc”, email: “abc@gmail.com” };
var result = (a != null && a != undefined) ? a : “not defined” ;
console.log(result); // { name: “abc”, email: “abc@gmail.com” }
OR
if(a != null && a != undefined) {
console.log(a);
} else {
console.log(“not defined”);
}
// output is : { name: “abc”, email: “abc@gmail.com” }
But now we can do that using ?? operator i.e. Nullish coalescing operator.
var a = { name: “abc”, email: “abc@gmail.com” };
var result = (a ?? “not defined”);
console.log(result); // { name: “abc”, email: “abc@gmail.com” }Nullish coalescing operator can be used with multiple values as well as below
var age = 25;
var height;
var email;var result = (height ?? email ?? age ?? “Not Defined”);
console.log(result); // 25
var result = (“Not Defined” ?? height ?? email ?? age);
console.log(result); // “Not Defined”
The difference between Nullish coalescing and OR (||) operator.
The OR operator returns true if condition is true but Nullish coalescing returns value if it’s defined otherwise returns undefined.
var age = 0;
var result = (age || 100);
console.log(result); // Here it returns 100 because age is 0 so it can be treated as false value.
result = (age ?? 100);
console.log(result); // Here it returns 0 because Nullish coalescing operator only check whether variable is defined.
It is not a good practice to use Nullish coalescing (??) with OR (||) and AND (&&) operator.
var a = 1 && 2 || 3 ?? 4 // Syntax error.
If you want to use ?? with || or && then precedence is need to be defined manually or explicitly.
So the above code can be works in below way,
var a = (((1 && 2) || 3) ?? 4) // output is 2
Summary:
- In short we can say that the Nullish coalescing operator returns the first defined value.
- Don’t use Nullish coalescing operator with && and || operator. If there is need then provide the precedence explicitly.
Reference link,
https://javascript.info/nullish-coalescing-operator