Middle
What is NaN and in what cases does it occur?
sobes.tech AI
Answer from AI
NaN (Not a Number) is a special value in JavaScript that indicates the result of an operation that does not produce a number. It occurs when a mathematical operation or conversion cannot return a valid numeric value.
Examples of when NaN occurs:
- Division of 0 by 0:
0 / 0. - Converting a non-numeric string to a number:
Number('abc'). - Result of invalid mathematical operations, such as taking the square root of a negative number:
Math.sqrt(-1).
It is important to note that NaN is not equal to itself (NaN !== NaN), so functions like isNaN() or Number.isNaN() are used for checking.
console.log(0 / 0); // NaN
console.log(Number('abc')); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // true