First things first, if you console log the type of NaN, you will get "number". People who are new to programming or the mathematical domain might wonder why something called "Not a Number" is actually considered a number? Because,
console.log(typeof(NaN)); // number
console.log('JS'/3) => NaN console.log(Math.sqrt(-1)) => NaN
In those cases, we get true as a result. But in the case of NaN, we get false. This may seem weird, but it's not entirely surprising. Let's say we got NaN because we tried to find the square root of -1. Then we tried to divide 0/0, and we will also get NaN.
let calculation_1 = 0/0 let calculation_2 = Math.log2(-2) let calculation_compare = calculation_1 === calculation_2 console.log(calculation_compare) => false
Now think for a moment. Although both calculations result in NaN, the actual results are completely different, and therefore represented by different NaN values. That's why we can't check the equality of NaN with NaN. Not only the equality operator (==), but other comparison operators like '>', '<', '!=' will also return false when comparing NaN values.
It is time for some real life example when we might get NaN.
console.log(1 * undefined) => NaN console.log(parseInt('john123')) => NaN console.log(1 NaN) => NaN console.log(0 * Infinity) => NaN console.log(Math.pow(-3, 0.5)) => NaN
In real-world applications, we may encounter failed calculations that can lead to undefined or NaN values. If we continue with these values without checking for NaN, we might not get our desired results.
That's why it's essential to understand the behavior of NaN and its use cases, so we can properly handle these undefined values and ensure that our calculations and functions are working correctly.
That's it today. Hoped you enjoyed the article. 👍