JavaScript's 'NaN': The Notoriously Awkward Numberπ


NaN is a global property in JavaScript that represents a value that is "Not a Number". Despite its name, NaN is still considered a numeric data type in JavaScript. If you check the data type of NaN using the 'typeof' operator, you'll find that it returns "number".
console.log(typeof NaN); // number
When comparing NaN using equality operators (== or ===), you may encounter a confusing behavior: NaN is not equal to itself. That means NaN == NaN and NaN === NaN both return false.
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
If you ever need to compare NaN values, what do you do? π
You have two solutions:
Use the isNaN() function.
Use the Number.isNaN() method.
Today, let's learn how to use isNaN(). This function takes a value as an argument. If the value is NaN, it returns true; otherwise, it returns false. You don't need to manually check if a value is NaN. JavaScript handles it automatically. Before performing any automatic conversions, JavaScript tries to convert the value using the Number() constructor function.
console.log(Number(10)); // 10
console.log(Number('Hello')); // NaN
The Number() constructor function tries to convert the argument into a number. If successful, it returns the number; otherwise, it returns NaN.
Now, let's see isNaN() in action:
console.log(isNaN(25)); // false
console.log(isNaN('Mirza')); // true
JavaScript can be quite confusing, and one tricky aspect is NaN (Not a Number). Understanding its concept can help you easily solve related problems π.
Feel free to run the following examples to better understand:
console.log(Number(undefined)); // NaN
console.log(Number({})); // NaN
console.log(Number(NaN)); // NaN
console.log(Number('NaN')); // NaN
console.log(Number(true)) // 1
console.log(Number('20')); // 20
console.log(Number(null)); // 0
console.log(Number([])); // 0
console.log(Number('')); // 0
console.log(Number(false)) // 0
That's it for today! If you have any confusion or questions, feel free to ask in the comments below ππ
Subscribe to my newsletter
Read articles from Mirza Mohibul Hasan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
