JavaScript Nullish Coalescing

Nullish Coalescing

In this article, you'll learn about Nullish Coalescing and explore its applications in JavaScript.

What is Nullish Coalescing?

Nullish Coalescing is a logical operator in JavaScript that returns the right-hand side operand when the left-hand side operand is null or undefined. If the left-hand side operand is neither null nor undefined, it returns the left-hand side operand.

The syntax looks like this:

const result = x ?? y;

Difference Between Nullish Coalescing and Logical OR (||)

At first glance, Nullish Coalescing may seem similar to the Logical OR (||) operator, but there are crucial differences.

The Logical OR operator returns the right-hand side operand if the left-hand side operand is falsy (e.g., false, 0, NaN, null, undefined, or an empty string).

However, the Nullish Coalescing operator only returns the right-hand side operand if the left-hand side operand is null or undefined. This distinction allows for a more accurate handling of default values.

Example so you can see it in action:

const x = 0;
const y = 69;

console.log(a || b); // Output: 69, because 0 is falsy
console.log(a ?? b); // Output: 0, because 0 is not null or undefined

Common Use Case: Working with Numeric Values

This is the most common area I find myself reaching for Nullish Coalescing.

Dealing with numeric values allows you to correctly handle cases where 0, NaN, or an empty string are valid inputs.


function calculateDiscount(price, discount) {
  const finalDiscount = discount ?? 10;
  return price - (price * finalDiscount / 100);

console.log(calculateDiscount(100, 0)); // Output: 100, since 0 is a valid discount

console.log(calculateDiscount(100)); // Output 90, since discount is undefined

console.log(calculateDiscount(100, 5)); // Output 95, since 5 is a valid number

console.log(calculateDiscount(100, "")); // Output 90, since ""/100 equals 0

console.log(calculateDiscount(100, "Hello")); // Output NaN, since "Hello"/100 equals NaN

I hope the final example gave you a better understanding of how helpful Nullish Coalescing can be (especially with JavaScript's quirky mathematic behavior).

Nullish Coalescing has become an essential tool in the modern JavaScript developer's toolkit with its ability to distinguish between null or undefined and other falsy values.

Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.