Skip to content

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

  • by

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

<!DOCTYPE html> 
<html>
  
<body> 
    <script> 
    num = NaN; 
    if(isNaN(num)) num = 0; 
    alert(num); 
</script> 
      
    
</body> 
  
</html> 

Output:

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:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   }
   return val;
}

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

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

if (isNaN(a)) a = 0;

It’s an annoying.

You can do this: Using || Operator:

a = a || 0

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.

a = a ? a : 0;

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

Your email address will not be published. Required fields are marked *