
Understanding the Nullish Coalescing Operator (??) in JavaScript
Mahmudul Hasan Nayeem / September 5, 2024
JavaScript is a language that continuously evolves, introducing new features that enhance its capabilities and make coding more intuitive. One of the relatively recent additions is the nullish coalescing operator (??). If you've been using JavaScript for a while, you've likely encountered scenarios where you need to assign default values to variables when they are null or undefined. This is where the ?? operator shines.
What is the Nullish Coalescing Operator?
The nullish coalescing operator (??) is a logical operator introduced in ECMAScript 2020 (ES11). It provides a way to assign default values to variables that are null or undefined. The operator works similarly to the logical OR (||) operator but with an important distinction: it only considers null or undefined as "nullish" values.
Here’s the syntax:
let result = expression1 ?? expression2;
- expression1: The value to be checked for nullish (either null or undefined).
- expression2: The default value to return if expression1 is nullish.
How is it Different from the ( || ) Operator?
Before ?? was introduced, developers often used the logical OR (||) operator to assign default values. However, this approach could lead to unintended behavior because || considers any falsy value (e.g., 0, NaN, false, "") as a reason to use the default value.
for example:
let count = 0
let result = count || 10
console.log(result) // 10
In this case, because count
is 0
(a falsy value), the OR operator assigns
10
to result
, even though count
is a valid value.
In contrast, the nullish coalescing operator only checks for null or undefined:
let count = 0
let result = count ?? 10
console.log(result) // 0
Here, count
is 0
, which is not null
or undefined
, so result
correctly
remains 0
.
Use Cases of the Nullish Coalescing Operator
-
Default Function Parameters: The
??
operator is particularly useful when setting default values for function parameters.function greet(name) { name = name ?? 'Guest' console.log(`Hello, ${name}!`) } greet() // "Hello, Guest!" greet('Alice') // "Hello, Alice!"
-
Handling Optional Values: When working with optional values or data that might be missing, the
??
operator provides a clean way to handle defaults.let userSettings = { theme: null, notifications: true } let theme = userSettings.theme ?? 'light' console.log(theme) // "light"
-
Simplifying Ternary Operations: The
??
operator can sometimes simplify ternary expressions used to check fornull
orundefined
.let input = null let output = input !== null && input !== undefined ? input : 'Default Value' console.log(output) // "Default Value" // With ?? operator let outputSimplified = input ?? 'Default Value' console.log(outputSimplified) // "Default Value"
Important Considerations
-
Operator Precedence: The nullish coalescing operator has lower precedence than most operators, including the logical AND
(&&)
and logical OR(||)
. Always be mindful of how expressions are evaluated and use parentheses if necessary.let result = true || false ?? "Default"; // Incorrect console.log(result); // true let correctedResult = (true || false) ?? "Default"; // Corrected console.log(correctedResult); // true
-
Combining with Other Operators: It's important to know that
??
cannot be directly combined with&&
or||
without parentheses because of potential syntax errors.let a = null; let b = "Hello"; let result = a ?? b && "World"; // Syntax Error
To avoid this, use parentheses:
let result = (a ?? b) && 'World' // "Hello"
Conclusion
The nullish coalescing operator (??
) is a powerful addition to JavaScript that
simplifies handling null
or undefined
values. By using it, you can avoid
common pitfalls associated with the logical OR operator, particularly when
working with falsy values like 0
or ""
. Understanding and using ??
in your
code can lead to more readable and reliable code, especially in cases where you
need to provide default values.
As with any feature, it's important to understand when and how to use the nullish coalescing operator effectively to write cleaner, more maintainable JavaScript.
0