Home ยป JavaScript ยป Convert NaN to 0 in JavaScript

Convert NaN to 0 in JavaScript

To change NaN to 0, use the logical OR (||) operator, as in const result = val || 0;. If the value to the left is false, the logical OR (||) operator returns the value on the right.

NaN to 0 JavaScript Examples

let val = NaN;

val = val || 0;

console.log(val); // Output 0

If the value to the left is false, the logical OR (||) operator returns the value on the right. JavaScript's false values are null, undefined, false, 0, "" (empty string), and NaN. (not a number).

This means that rather than explicitly determining whether a value is NaN, we instead determine whether it is false. Thus, it might be a null value, an empty string, or undefined one. The value to the right of the operator is a fallback value in the event that the value to the left is false, which is a simple way to think about it. As an alternative, you can consciously determine whether the value is NaN.

let val = NaN;

if (Number.isNaN(val)) {
  val = 0;
}

console.log(val); // Output 0

We can reassign the val variable if the stored value is NaN by declaring it with the let keyword. Even though this method is a little more verbose, it is still simple to read and makes sense. A ternary operator is an additional option. To change NaN to zero, use the ternary operator, such as const result = Number. 0: val; isNaN(val). The operator returns 0 if the value is NaN; otherwise, the value is returned.

let val = NaN;

const result = Number.isNaN(val) ? 0 : val;

console.log(result); // Output 0

The ternary operator resembles an if/else statement greatly. The value to the left of the colon is returned if the expression to the left of the question mark evaluates to a true value; otherwise, the value to the right is returned. To determine whether the value is NaN, note that we used the Number.isNaN method (not a number). Due to the fact that NaN is the only value in JavaScript that is not equal to itself, you shouldn't attempt to compare directly to it.

console.log(NaN === NaN); // Output false

Any other value you try to compare to itself will return true, but this is not the case with NaN.

Summary

NaN is the only value in JavaScript that is not equal to 0. To change NaN to 0, use the logical OR (||) operator or the ternary operator. The operator returns 0 if the value is NaN and 1 if it is not.

See also: