Sitemap
Nikhil K

Nikhil K

Understanding the Nullish Coalescing Operator (??) in JavaScript

2 min readSep 5, 2025
Press enter or click to view image in full size

JavaScript has several operators that help us deal with values, especially when they might be null or undefined. One of the most useful among them is the Nullish Coalescing Operator (??), introduced in ES2020.

What is the Nullish Coalescing Operator?
The ?? operator provides a way to set a default value when a variable is either:

  • null
  • undefined

In other words, ?? only checks for nullish values (null or undefined), unlike the logical OR operator (||) which also treats other falsy values (like 0, false, "") as false.

syntax

If value1 is not nullish, the result is value1.
If value1 is null or undefined, the result is value2.

Get Nikhil K’s stories in your inbox

Join Medium for free to get updates from this writer.

Basic Usage:

Press enter or click to view image in full size
Here, since name is null, the operator falls back to “Guest”.

Difference Between || and ??

Press enter or click to view image in full size
This is the biggest advantage of ??. It doesn’t override valid values like 0, false, or “”.

Multiple Chaining

Press enter or click to view image in full size
You can chain multiple ?? operators to provide several fallback options.

With Functions

Press enter or click to view image in full size
This is especially useful when working with optional function parameters.

Important Rule: Operator Precedence
?? has lower precedence than most operators but higher than =.
You cannot mix ?? with || or && without parentheses:

Press enter or click to view image in full size

Conclusion
The Nullish Coalescing Operator (??) makes your JavaScript code cleaner and safer when dealing with potentially missing values. Unlike ||, it respects valid falsy values like 0, false, and “”.

--

--