DEV Community

Cover image for What is an NaN error in JavaScript?
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

What is an NaN error in JavaScript?

keyboard

Have you ever wondered what is NaN error coming in your project? πŸ€”

Today, in this article I am going to discuss the NaN error in detail.

Let's get started πŸš€

In JavaScript, NaN stands for Not a Number.
This error occurs when you parse something to a number that is not a number

Let's see it with an example,

var helloWorld = parseInt(helloWorld);
Enter fullscreen mode Exit fullscreen mode

This will return NaN

didn't get it? No problem let's get a little simpler

var helloWorld = parseInt("Hello World");
Enter fullscreen mode Exit fullscreen mode

"Hello World" is a string and we are parsing to an integer but that is not possible therefore the browser will return NaN

isNan() Method

isNan() will return true if a value is NaN
example

isNaN(18)
// false
isNaN(18.81)
// false
isNaN("JavaScript")
// true
isNaN("233.3")
// false
isNaN('17/01/2022')
// true
Enter fullscreen mode Exit fullscreen mode

As you can see numbers will return false as they are not NaN even if, the number is in the form of string.
Any string (word or sentence) will return true as it is NaN

Me when isNaN("123") showing false:
confusing

What about you? Comment πŸ‘‡

wait a minute

Here comes, something that contradicts

As discussed earlier, isNan() will return true if a value is Not-a-Number(NaN)
Number.isNaN() method while is completely opposite of isNaN method, here Number.isNaN() will return true if number is NaN

Let's go with an example,

isNaN('JavaScript')
// true
Number.isNaN('JavaScript')
// false
Enter fullscreen mode Exit fullscreen mode
isNaN(18)
// false
Number.isNaN(18)
// true
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, have a nice day!

Top comments (0)