Convert NaN to 0 in JavaScript | Using isNan() method OR other method

Use isNan() method to Convert NaN to 0 in javascript. This method checks the given number is NaN or not. NaN means in JavaScript is “Not a Number”.

When you can expect the NaN Error in JS?

One of the common situations when you try to convert string number to number but the string has character. It will indicate a NaN (Not a Number) error.

Example of How to convert NaN to 0 in JS


Convert NaN to 0 in JavaScript

Write a function to convert NaN to 0 in JavaScript

Here is example code, and use it everywhere want a number value:

Q: How to convert NaN values to 0 without an if statement?

Answer: Using if statement you need to check my variables every time.

It’s an annoying.

You can do this: Using || Operator:

which will convert a from any “falsey” value to 0.

The “falsey” values are:

  • false
  • null
  • undefined
  • 0
  • "" ( empty string )
  • NaN ( Not a Number )

Using ternary operator:

Number is checked via ternary operator, similar to 1, if NaN it converts to 0.

Or this if you prefer: Same effect as above.

Do comment if you have any doubts on this this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.