NaN is a global property in JavaScript which 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(10)); // false
console.log(isNaN('Hello')); // 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(10)); // 10
console.log(Number('Hello')); // NaN
console.log(Number('5')); // 5
console.log(Number(NaN)); // NaN
console.log(Number('NaN')); // NaN
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
console.log(Number({})); // NaN
console.log(Number([])); // 0
console.log(Number('123ABC')); // NaN
console.log(Number('')); // 0
console.log(Number(true)) // 1
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 😎😎
Top comments (0)