Nullish Coalescing Operator

Posted on May 26, 2020

Written by Preston Lamb

javascript

tldr;

The nullish coalescing operator is a relatively new operator in JavaScript. It’s use is similar to the OR operator, but with a minor difference that can be useful in many situations. With the OR operator, JavaScript uses the first truthy value it finds in the statement. If a part of the statement is falsy, JavaScript moves on. The nullish coalescing operator is similar, except it doesn’t move on to the next part of the JavaScript statement on every falsy value. It only moves on for null and undefined.

Nullish Coalescing Operator

The nullish coalescing operator is denoted by two question marks ??. When using it, what you’re saying is that you want to use the left value in the statement is if it’s not null or undefined. If so, move on to the right value in the statement. This is similar to the OR operator, except that with the OR operatorJavaScript moves to the right side of the statement on any falsy value. Here’s an example of the two operators in use:

const result1 = 0 || 5;
console.log(result1); // 5
const result2 = 0 ?? 5;
console.log(result2); // 0

In the first part of the above example the statement says to use 0 or 5, whichever one first gives a truthy value as the result. 0 is falsy, so it moves on to the 5. 5 is truthy, so that’s the result. In the second part of the example, the statement again says to use 0 or 5, but in this case it uses the nullish coalescing operator. 0 is falsy, but since it’s not null or undefined, it’s a valid result for the statement. 0 is returned as the result of the statement.

That’s all there is to the nullish coalescing operator. It’s pretty straight forward, and will be really helpful going forward in JavaScript applications. There are times when a falsy value like 0 is a valid result. For example, if you’re writing code for a game, a score of 0 is valid. But the following statement with the OR operator wouldn’t give us the result we want:

const score = 0 || 10;
console.log(score); // 10

But with the nullish coalescing operator we can set a score to 0:

const score 0 ?? 10;
console.log(score); // 0

We no longer need to write out entire if statements or complicated ternary statements to check for just null or undefined.

Conclusion

This new operator will help out a lot in JavaScript applications going forward. It should be familiar to use, as it’s similar to other logical operators in JavaScript. But the difference in purpose is very nice and it solves a real problem in our code.

Click here to subscribe to the newsletter and be the notified when a new blog post is available!