Categories
JavaScript Answers

How to Check That a Number is NaN in JavaScript?

Spread the love

The isNaN Function

We can use the isNaN function to check whether a number is NaN .

For instance, we can write:

const nan = isNaN(parseFloat("abc"))  
console.log(nan)

isNaN will try to parse the argument we pass into it automatically to a number.

But to be safe, we can parse it ourselves with parseFloat first to make sure we get the expected result.

We parseFloat should return NaN since we passed in a non-numeric string into it.

So isNaN should return NaN .

Therefore, nan is true .

Check Whether a Value Equals Itself

Since NaN is the only value in JavaScript which doesn’t equal itself, we can check whether a variable equals itself to check if the variable’s value is NaN .

For instance, we can write:

const nan = NaN  
console.log(nan !== nan)

Then the console log will show true since NaN doesn’t equal itself.

If nan has any other value, the console log would log false .

So if we have:

const nan = true  
console.log(nan !== nan)

Then the console log would show false .

The Number.isNaN Method

The Number.isNaN method is another method that lets us check whether a value we pass into it is NaN .

The difference between isNaN and Number.isNaN is that Number.isNaN doesn’t try to convert a value to a number before it’s checked.

For instance, we can write:

const nan = Number.isNaN('abc');  
console.log(nan)

Then console log shows false since we didn’t pass in NaN .

We just passed in something that’s not a number.

But if we write:

const nan = Number.isNaN(NaN);  
console.log(nan)

Then nan is true .

Object.is

Another method we can use to check for NaN is the Object.is method.

Object.is takes 2 arguments with the values that we want to compare.

If both values are NaN , then it returns true instead of false like we have with === .

For instance, we can write:

const a = NaN  
const nan = Object.is(a, NaN);  
console.log(nan)

Then nan is true according to the console log.

Conclusion

We can check for NaN with various functions and methods provided by JavaScript.

Also, we can use the === operator to check if a value doesn’t equal itself.

If it doesn’t, then we know the value must be NaN since NaN is the only value that doesn’t equal itself in JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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