Middle
What is NaN? Provide examples when NaN occurs. How to check if a value is NaN?
sobes.tech AI
Answer from AI
NaN (Not a Number) is a special value in JavaScript that indicates the result of a non-numeric operation with numbers.
Examples of NaN occurrence:
- Result of an operation with non-numeric strings:
parseInt("abc")returnsNaN. - Division of 0 by 0:
0 / 0isNaN. - Result of mathematical operations with
undefined:undefined * 5isNaN.
Checking for NaN:
- The standard way is to use the function
Number.isNaN(value), which returnstrueonly if the value is trulyNaN. - It is not recommended to use the global function
isNaN(), as it converts the argument to a number and may returntruefor non-numeric values.
Example:
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("abc")); // false
console.log(isNaN("abc")); // true (undesirable behavior)
Thus, NaN is an indicator of an error or an undefined numeric result, and it is better to use Number.isNaN() for checking.