const - JS | lectureData Structures, Modern Operators & Strings

The Nullish Coalescing Operator (??)

Data Structures, Modern Operators & Strings

Let's now learn about this new operator with the funny name of Nullish Coalescing operator. In the last lecture, we used the OR operator to set a default value in case the first value was a falsy value.

Below is the code we had in the previous lecture:

restaurant.numGuests = 0;

const numberOfGuests = restaurant.numGuests || 10;
console.log('RESULT = ', numberOfGuests);

NCO - 1

Just to recall what happened here, we noticed that on line one when we set numberOfGuests to zero, then JavaScipt will still take the default value of 10 and assign it to numberOfGuests because zero is a falsy value. Hence going to the second operand.

However, fortunately for us, there is a very good solution to this, and that's the Nullish Coalescing operator. It's an operator that was introduced in ES2020, and it works the following way:

// If you comment this line the result will be the default value (10)
restaurant.numGuests = 0;

// It works almost the same way as the OR operator but it will fix our error

const numberOfGuests = restaurant.numGuests ?? 10;console.log('RESULT = ', numberOfGuests);

NCO - 2

You can see that we now get our expected result which is zero. The value given to numberOfGuests on line 1. Now, to explain why this works, it's because the nullish coalescing operator works with the idea or with the concept of nullish values instead of falsy values.

Nullish values are null and undefined. It does not include zero or the empty string. So basically, for the nullish coalescing operator, it is as if the zero and the empty string were not falsy values but were truthy values.

To finish and just to recap, the nullish coalescing operator works with the principle of nullish values. Hence, all the nullish values will short circuit the above solution. So only if restaurant.numGuests was null or undefined, only then the second operand (10) would be executed and returned.

It's a really great and useful operator, even though right now, it might not seem useful.