Nullish coalescing operator

Mayur Palase
2 min readApr 10, 2021

--

Nullish coalescing operator ‘??’
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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mayur Palase
Mayur Palase

No responses yet

Write a response