Convert NaN to 0 using JavaScript

Last updated: Dec 23, 2021

Check out my new book

Convert NaN to 0 using JavaScript#

Use the logical OR (||) operator to convert `NaN` to `0`, e.g. `const result = val || 0;`. The logical OR (||) operator returns the value to the right if the value to the left is falsy.

index.js
```Copied!```let val = NaN;

val = val || 0;

console.log(val); // 👉️ 0
``````

The logical OR (||) operator returns the value to the right if the value to the left is falsy.

The falsy values in JavaScript are `null`, `undefined`, `false`, `0`, `""` (empty string), `NaN` (not a number).

This means that we don't explicitly check if the value is equal to `NaN`, we check that the value is falsy. So it could be an empty string, `undefined`, `null`, etc.

An easy way to think about it is - the value to the right of the operator is a fallback in case the value to the left is falsy.

Alternatively, you can explicitly check if the value is `NaN`.

index.js
```Copied!```let val = NaN;

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

console.log(val); // 👉️ 0
``````

Declaring the `val` variable with the `let` keyword allows us to reassign it if the stored value is equal to `NaN`.

While this approach is a little more verbose, it's still easy to read and intuitive.

Alternatively, you can use the ternary operator.

Use the ternary operator to convert `NaN` to zero, e.g. `const result = Number.isNaN(val) ? 0 : val;`. If the value is equal to `NaN`, the operator returns `0`, otherwise the value is returned.

index.js
```Copied!```let val = NaN;

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

console.log(result); // 👉️ 0
``````

The ternary operator is very similar to an `if/else` statement.

If the expression to the left of the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right is returned.

Note that we used the Number.isNaN method to check if the value is `NaN` (not a number).

You shouldn't try to explicitly compare to `NaN` because `NaN` is the only value in JavaScript, which is not equal to itself.

index.js
```Copied!```console.log(NaN === NaN); // 👉️ false
``````

Any other value you try to compare to itself, you would get `true` back, however this is not the case with `NaN`.

Use the search field on my Home Page to filter through my more than 3,000 articles.