NaN Data Type
console.log(NaN === NaN); // Output: false
In the above code snippet, we are comparing two NaN values using the strict equality operator (===). Surprisingly, the comparison returns false because NaN is not equal to itself.
To check if a value is NaN, we can use the isNaN() function:
console.log(isNaN(NaN)); // Output: true console.log(isNaN(10)); // Output: false
The isNaN() function returns true if the passed value cannot be converted to a valid number; otherwise, it returns false.
NaN and Arithmetic Operations
When performing arithmetic operations involving NaN, the result will always be NaN:
console.log(NaN + 5); // Output: NaN console.log(NaN * 10); // Output: NaN console.log(Math.sqrt(NaN)); // Output: NaN
In the above examples, adding 5 to NaN or multiplying it by 10 both result in NaN. Even taking the square root of NaN using Math.sqrt() returns NaN.
To determine if a value is NaN without using the isNaN() function, we can use the Number.isNaN() method introduced in ECMAScript 2015:
console.log(Number.isNaN(NaN)); // Output: true console.isNaN(10)); // Output: false
The Number.isNaN() method returns true if the passed value is NaN; otherwise, it returns false. Unlike the global isNaN() function, Number.isNaN() does not try to convert non-number values to numbers before checking for NaN.
NaN is not equal to any other value, including itself. When performing arithmetic operations with NaN, the result will always be NaN. We can use the isNaN() function or Number.isNaN() method to check if a value is NaN.