What is nullish coalescing and how does it work?

What is nullish coalescing and how does it work?

Table of contents

No heading

No headings in the article.

Nullish coalescing(??) is a logical operator introduced in ES6+ which can be used to provide a default value if the value is null or undefined. It will first check the value of the left-hand side operand and if that evaluates to null or undefined then it will resolve to the value of right-hand side operand.

The syntax for nullish coalescing looks like this:

      let name;

      let result = name ?? "Joe" ;

      console.log(result); //"Joe"

In the above example, the name variable has not been assigned any value so it evaluates to undefined and so the result is set to the default value provided at the right-hand side operand and thus it consoles "Joe".

Prior to the introduction of nullish coalescing, the OR operator( || ) was used sometimes to achieve the same result. But OR operator works a bit differently, it returns the right-hand side operand whenever the left-hand side operand is any falsy value and not only null or undefined. It treats values like an empty string(' '), false, 0 as falsy values and therefore may lead to some unexpected results if you need to consider these values as valid.

For example:

let num = 0 || 10; //returns 10
let str = ' ' || "default value"; //returns "default value" 
let checkFalse = false || "Not falsy" ; //returns "Not falsy"

As we can see, the OR operator returns the right-hand side operand even if the left-hand side operand is not null or undefined. In such cases, nullish coalescing can be useful as it will not evaluate the right-and side operand if the left-hand operand is neither null nor undefined.

let fruit = ' ' ?? "Apple";
let someNumber = 0 ?? 22;
let dummyText = undefined ?? "Some default text";
let getFalsy = false ?? true;

console.log(fruit); // returns ' '
console.log(someNumber); // returns 0
console.log(dummyText); //returns "Some default text"
console.log(getFalsy); // returns false

In the above examples, we saw that nullish coalescing operator only evaluates the right-hand side operand when the left-hand side operand is undefined.

I hope this helps you understand the nullish coalescing operator a little bit better!

If this helped you in understanding JavaScript in a better way, make sure to share it with others and appreciate it with likes and comments.

Did you find this article valuable?

Support Sakshi Chaudhary by becoming a sponsor. Any amount is appreciated!