Sobes.tech
Junior — Middle

How can it be determined whether a variable contains a Not-a-Number (NaN) value?

sobes.tech AI

Answer from AI

In JavaScript (and Node.js), to check if a variable contains the value NaN, you can use the function Number.isNaN(). It returns true only if the argument is truly NaN, unlike the global function isNaN(), which tries to convert the argument to a number and may return true for non-numeric values.

Example:

const value = NaN;
console.log(Number.isNaN(value)); // true

const notANumber = "abc";
console.log(Number.isNaN(notANumber)); // false
console.log(isNaN(notANumber)); // true, because "abc" cannot be converted to a number

You can also check for NaN using the property that NaN is not equal to itself:

const value = NaN;
console.log(value !== value); // true

This is a trick often used to check for NaN.

How can it be determined whether a variable contains… - sobes.tech