Understanding the Nullish Coalescing Operator (??) in JavaScript
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:
nullundefined
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:
Difference Between || and ??
Multiple Chaining
With Functions
Important Rule: Operator Precedence
?? has lower precedence than most operators but higher than =.
You cannot mix ?? with || or && without parentheses:
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 “”.






