Nullish Coalescing (??) - Handle Defaults the Right Way
Source: Dev.to
Introduction
Before ES2020, developers mostly relied on the logical OR (||) operator for default values.
const currentPage = pageFromApi || 1;
The || operator treats all falsy values as invalid:
0''(empty string)falsenullundefined
Example: Logical OR replaces a valid value
// User is on page 0 (first page)
const pageFromApi = 0;
// WRONG: page 0 gets replaced
const page = pageFromApi || 1;
console.log(page); // Output: 1
Page 0 is a valid value, but || treats it as falsy.
The Nullish Coalescing Operator (??) was introduced in ES2020 to solve this exact problem.
Syntax
const result = value ?? defaultValue;
Examples
Using Nullish Coalescing – correct handling of 0
// User is on page 0 (first page)
const pageFromApi = 0;
// CORRECT
const page = pageFromApi ?? 1;
console.log(page); // 0
Function comparison: OR logic vs. Nullish Coalescing
OR Logic
function getUsername(user) {
if (user.name === null || user.name === undefined) {
return "Guest";
} else {
return user.name;
}
}
// OUTPUT examples:
getUsername({ name: "Chhavi" }); // "Chhavi"
getUsername({ name: "" }); // ""
getUsername({ name: null }); // "Guest"
getUsername({}); // "Guest"
Nullish Coalescing
function getUsername(user) {
return user.name ?? "Guest";
}
// OUTPUT examples:
getUsername({ name: "Chhavi" }); // "Chhavi"
getUsername({ name: "" }); // ""
getUsername({ name: null }); // "Guest"
getUsername({}); // "Guest"
Conclusion
- Nullish Coalescing (
??) treats0,false, and''as valid values, making it ideal for handling API responses or optional configurations. - Logical OR (
||) triggers a default for any falsy value.
Using ?? often results in fewer lines of code while preserving legitimate falsy values.