When developing web applications, there might be cases you want to treat falsy values like null
, NaN
, undefined
, and false
as 0
(for instance, If you have variables or properties that can have these values, assigning them 0
as a default value simplifies handling and avoids potential errors or unexpected behavior in subsequent operations).
This pithy, example-based article will show you a few different ways to convert null
, NaN
, undefined
, and false
to 0
in modern JavaScript.
Using the logical OR operator (||
)
What we will do is use the logical OR operator (||
) along with the assignment operator (=
) to replace the falsy values with 0.
Example:
let value1 = null;
let value2 = undefined;
let value3 = false;
let value4 = NaN;
value1 = value1 || 0;
value2 = value2 || 0;
value3 = value3 || 0;
value4 = value4 || 0;
console.log("value1: ", value1); // 0
console.log("value2: ", value2); // 0
console.log("value3: ", value3); // 0
console.log("value4: ", value4); // 0
This is the most concise and elegant approach. However, the other approaches in the article are also worth knowing.
Using conditional (ternary) operator (?
and :
)
This solution uses the conditional (ternary) operator to conditionally assign the value 0 if it is null
, NaN
, undefined
, or false
. It is more verbose than the preceding technique but provides flexibility for additional conditions or fallback values (as needed).
Example:
// define a function that converts falsy values to zero
const falsyToZero = (value) => {
return (value === null || isNaN(value) || value === false) ? 0 : value;
}
// try it out
let value1 = null;
let value2 = undefined;
let value3 = false;
let value4 = NaN;
console.log(falsyToZero(value1)); // 0
console.log(falsyToZero(value2)); // 0
console.log(falsyToZero(value3)); // 0
console.log(falsyToZero(value4)); // 0
Using the Number() function and the Number.isNaN() method
This technique offers explicit type conversion and utilizes a built-in method for checking NaN
. The process consists of 3 steps:
- Use the
Number()
function to explicitly convert the value to a number (the result can be0
orNaN
). - Check if the converted value is
NaN
using theNumber.isNaN()
method. - If it is
NaN
, assign it to0
; otherwise, keep the original value.
Code example:
// define a function that converts falsy values to zero
const falsyToZero = (value) => {
let result = Number(value);
if(Number.isNaN(result)){
result = 0;
}
return result;
};
// try it out
let value1 = null;
let value2 = undefined;
let value3 = false;
let value4 = NaN;
console.log(falsyToZero(value1)); // 0
console.log(falsyToZero(value2)); // 0
console.log(falsyToZero(value3)); // 0
console.log(falsyToZero(value4)); // 0
That’s it. Happy coding & have a nice day!