DEV Community

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

Posted on Edited 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);
🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini 🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini

This will return NaN

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

var helloWorld = parseInt("Hello World");
🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini 🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini

"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
🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini 🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini

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
🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini 🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini
isNaN(18)
// false
Number.isNaN(18)
// true
🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini 🔥 Jadwal & Hasil: dhairyashah/what is an nan error in javascript fb - Pertandingan Hari Ini

Thank you for reading, have a nice day!

Top comments (0)