Skip to content

How to convert NaN to number in JavaScript | Example code

  • by

You can convert NaN to a number by using the direct JavaScript method. But using the isNaN() method can check whether the given number is NaN or not. if isNaN() returns true(means its not a number) you can assign whatever number you need to that variable

<script>
	number = NaN;
	if (isNaN(number)) number = 0;
	console.log(number);
</script>

Convert NaN to number in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    num = NaN;

    if( isNaN(num) ){
      num =1000;
    }
    console.log(num);

  </script>

</body>
</html> 

Output:

How to convert NaN to number in JavaScript

Using || Operator: If “number” is any falsey value, it will be assigned to 0.

<script>
    number = NaN;
    number = number || 0;
    console.log(number);
</script>

Using ternary operator: similar to 1, if NaN it converts to 0.

<script>
    number = NaN;
    number = number ? number : 0;
    console.log(number);
</script>

Comment if you have any doubts or suggestions on this JS NaN topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading