How to Convert null, undefined, or NaN to 0 in JavaScript
When working with data from external sources or performing calculations, you often encounter values that are not numbers, such as null, undefined, or NaN (Not-a-Number). To prevent these from causing errors in your application, a common practice is to provide a "fallback" or default value, which is often 0.
This guide will teach you the modern and most effective methods for this task. You will learn how to use the Nullish Coalescing Operator (??) for handling null and undefined, and the Logical OR Operator (||) for handling all "falsy" values, including NaN.
The Core Problem: Handling "Empty" vs. "Invalid" Values
It's important to distinguish between two types of "non-values":
- Nullish Values: These are
nullandundefined. They typically represent the absence of a value. - Falsy Values: This is a broader category that includes
null,undefined,NaN,0,""(empty string), andfalse.
The operator you choose depends on which of these categories you want to handle.
Method 1 (Recommended): The Nullish Coalescing Operator (??)
Introduced in ES2020, the nullish coalescing operator (??) is the modern and most precise tool for providing a default value. It is specifically designed to only trigger for null or undefined.
The logic:
- The
??operator returns the right-hand side operand only if the left-hand side operand isnullorundefined. Otherwise, it returns the left-hand side operand.
For example, we have variables that might be null or undefined, and we want to convert them to 0 without affecting other valid values like 0 or an empty string.
// Problem: How to replace only null/undefined with 0?
let userScore = null;
let gameCount = 0; // This is a valid value we want to keep.
The solution:
let userScore = null;
let gameCount = 0;
let userName = '';
// Converts null to 0
const finalScore = userScore ?? 0;
console.log(finalScore); // Output: 0
// Does NOT change 0
const finalCount = gameCount ?? 10;
console.log(finalCount); // Output: 0
// Does NOT change an empty string
const finalName = userName ?? 'Guest';
console.log(finalName); // Output: ""
This operator is the best choice when you want to treat 0 and "" as valid values.
Method 2 (for Falsy Values): The Logical OR Operator (||)
The logical OR operator (||) has long been used as a way to provide default values. It returns the right-hand side operand if the left-hand side operand is any falsy value.
The logic:
- This is a good choice when you want to treat
null,undefined,NaN,0, and""all as invalid values that should be replaced.
The problem:
We have a calculated value that might result in NaN, and we want to default it to 0.
// Problem: How to handle NaN and other falsy values?
const calculatedValue = parseInt('abc'); // This results in NaN
const zeroValue = 0;
The solution:
const calculatedValue = NaN;
const zeroValue = 0;
const nullValue = null;
// Converts NaN to 0
const finalValue = calculatedValue || 0;
console.log(finalValue); // Output: 0
// Also converts 0 to 0 (or whatever is on the right)
const finalZero = zeroValue || 10;
console.log(finalZero); // Output: 10 (This is an important difference from ??)
// Also converts null to 0
const finalNull = nullValue || 0;
console.log(finalNull); // Output: 0
Because the || operator treats 0 as a falsy value, it is less precise than ?? and can lead to bugs if 0 is a valid input in your application.
A Note on Old Methods: The Ternary Operator and if Statements
Before these modern operators were common, this problem was solved with more verbose code.
- Ternary Operator:
let finalValue = (val === null || val === undefined) ? 0 : val; ifStatement:if (val == null) { val = 0; }(using== nullcleverly checks for bothnullandundefined).
While these methods still work, the ?? and || operators are far more concise and are the recommended best practice in modern JavaScript.
Conclusion: Which Operator Should You Use?
Choosing the right operator is simple once you know the difference.
- Use the Nullish Coalescing Operator (
??) when you want to replace onlynullorundefinedand want to preserve other falsy values like0and""as valid. This is the safest and most recommended choice for most situations. - Use the Logical OR Operator (
||) when you want to provide a fallback for any falsy value, includingnull,undefined,NaN,0, and"". This is useful for handling invalid calculations or empty strings.