JavaScript
Check for NaN without coercion
Use Number.isNaN when you want to know whether a value is specifically the numeric NaN value. It does not coerce arbitrary strings or objects into numbers first.
Worked example
Node.js example · save as example.mjs and run node example.mjs
console.log(Number.isNaN(NaN));
console.log(Number.isNaN("hello"));
console.log(Number.isNaN(Number("hello")));How it works
The first call is true because the input already is NaN. The second is false because the input is text. The third is true because Number converts the invalid numeric string into NaN before the check. Keeping conversion explicit makes validation easier to audit.
Limits and mistakes
NaN checks alone do not reject Infinity or enforce a numeric type. For ordinary finite measurements, Number.isFinite is often a better requirement. NaN also compares unequal to itself, so normal equality is not a useful test.
Check the result
Expect true, false, true. Add Infinity, null, and an empty string to your conversion tests so you do not accidentally accept values that only become numeric through coercion.
Sources
Reference documentation for the behavior used in this guide: