JavaScript NaN and Finite Checks without Coercion
Quick answer
NaN is a Number value representing an invalid or indeterminate numeric result. It is not equal to itself with strict equality.
How it works
Number.isNaN(value) is true only for the NaN Number. Global isNaN(value) converts its argument to Number first; invalid numeric text can therefore pass that test. Number.isFinite(value) accepts only finite Numbers, whereas global isFinite coerces before checking. Global coercion can itself throw for some inputs.
console.log(Number.isNaN("bad"), isNaN("bad"));console.log(Number.isNaN(0/0));Expected output in Node.js:
false truetrueThe global predicate coerces the string; the static predicate does not.
console.log(Number.isFinite("12"), isFinite("12"), Number.isFinite(Infinity));Expected output in Node.js:
false true falseThe global finite check converts text; infinity is nonfinite.
Common mistakes
Use a noncoercive predicate when validating already parsed values. NaN is not a string, null, or an exception by itself.
Practice
Compare static and global predicates for numeric text, invalid text and actual NaN.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript NaN and Finite Checks without Coercion — Knowledge Check
Apply the taught concept and predict the output.
Which check is true for NaN without coercing an arbitrary input?
Which expression checks whether a value is already a finite Number?
What is typeof NaN?
What is the exact console output in JavaScript NaN and Finite Checks without Coercion example 1?
console.log(Number.isNaN("bad"), isNaN("bad"));console.log(Number.isNaN(0/0));What is the exact console output in JavaScript NaN and Finite Checks without Coercion example 2?
console.log(Number.isFinite("12"), isFinite("12"), Number.isFinite(Infinity));