DEV Community

Cover image for Understanding JavaScript Nullish Coalescing Operator (??)
Shefali
Shefali

Posted on • Originally published at shefali.dev

Understanding JavaScript Nullish Coalescing Operator (??)

The Nullish Coalescing Operator (??) is a feature in JavaScript that was introduced in ECMAScript 2020. Using this operator you can handle default values for variables that might be null or undefined.

Before its introduction, the logical OR operator (||) was commonly used for this purpose, but it wasn’t always suitable because it handles all falsy values. The ?? operator provides a more precise and clearer alternative.

In this article, you’ll learn the concept of the Nullish Coalescing Operator, its advantages, how to use it, and some examples.

Let’s jump right into it!🚀

What is the Nullish Coalescing Operator (??)?

The nullish coalescing (??) operator is a logical operator, which is used to check if a value is null or undefined.

If its left-hand side operand is null or undefined, then it returns its right-hand side operand (fallback value).

If its left-hand side operand is not null or undefined, then it returns the left-hand side operand.

For example:

let userInput = null;
let inputValue = userInput ?? 'default';
console.log(inputValue); // Output: default
Enter fullscreen mode Exit fullscreen mode

In this example, userInput is null, so the ?? operator returns the fallback value 'default'.

Now, you might be thinking how is it different from the logical OR || operator?🤔

This is different from the logical OR || operator, because the || operator returns the right-hand side operand if the left-hand operand is any falsy value (like false, 0, '', NaN, etc.), not only null or undefined. While the ?? operator only focuses on the null or undefined.

Why use Nullish Coalescing (??) operator instead of Logical OR (||) operator?

The ?? operator only focuses on null and undefined values, while the || operator checks for all falsy values (like false, 0, '', NaN, etc.), which can lead to unexpected results.

For example:

let obj = {};
let value = obj.age ?? 'default value';
console.log(value); // Output: default value
Enter fullscreen mode Exit fullscreen mode

In this example, age is undefined in the object, so the ?? operator returns the fallback value 'default value'.

Now, let’s take another example to understand this better.

let userInput = '';
let inputValue = userInput ?? 'default';
console.log(inputValue); // Output: <empty string>
Enter fullscreen mode Exit fullscreen mode

In this example, userInput is an empty string, which is a falsy value and not null or undefined, so the ?? operator returns <empty string>.

Now let’s see what happens if you use || instead of ??.

let userInput = '';
let inputValue = userInput || 'default';
console.log(inputValue); // Output: default
Enter fullscreen mode Exit fullscreen mode

Here, the || operator returns default, because it checks any falsy value.

Another reason for using ?? instead of || operator is readability.

Code using ?? is generally clearer and more readable because its purpose is directly linked to handling null and undefined. It provides a fallback value when a variable is null or undefined, making the code more readable and less prone to errors.

Nullish operator ?? with logical operators AND/OR

You can also use the ?? operator with other logical operators to check multiple conditions.

For example:

let userInput = null;
let inputValue = userInput ?? 'default' || 'alternative';
console.log(inputValue); // Output: default
Enter fullscreen mode Exit fullscreen mode

In this example, inputValue gets the value 'default' because the left-hand operand (userInput) is null.

Now let’s see what happens if userInput is not null.

let userInput = '';
let inputValue = userInput ?? 'default' || 'alternative';
console.log(inputValue);
Enter fullscreen mode Exit fullscreen mode

Nullish Coalescing Operator

Oops!! This throws an error😬😬

But why does this happen?🤔

This happens because the Nullish Coalescing Operator (??) cannot be used directly within logical operators like || OR and && AND without proper parenthesis around it.

The reason for that is JavaScript has specific rules for operator precedence, which refers to the priority levels of different operators, which means the order in which operations are evaluated.

For example: ?? has a lower precedence than || and &&, so placing it inside parentheses ensures it’s evaluated first within logical expressions.

So the correct way to use ?? directly with logical operators:

let userInput = '';
let inputValue = (userInput ?? 'default') || 'alternative';
console.log(inputValue); // Output: alternative
Enter fullscreen mode Exit fullscreen mode

Here, the parentheses force JavaScript to evaluate the ?? operation first, and after that the result is used in the logical OR operation with 'alternative'.

Conclusion

In JavaScript, the Nullish Coalescing Operator (??) provides a more clear and consistent way of handling default values for null and undefined. It avoids the pitfalls of the || operator by not returning unintended falsy values. Using Nullish Coalescing Operator (??) can make your code cleaner, more readable, and less prone to errors, especially when it comes to optional values. Understanding and using Nullish Coalescing Operator (??) can lead to more efficient and maintainable code.

That’s all for today.

I hope it was helpful.

Thanks for reading.

Here are 45 More JavaScript Tips & Tricks for Developers.

For more content like this, click here.

Follow me on X(Twitter) for daily web development tips.

Keep Coding!!

Buy Me A Coffee

Check out toast.log, a browser extension that lets you see errors, warnings, and logs as they happen on your site - without having to open the browser's console. Click here to get a 25% discount on toast.log.

Top comments (0)