JavaScript Interview Question #15

What is the difference between Number.isNaN() and isNaN()?

JavaScript Fundamentals, Types, Scope & Functions Junior Beginner

Quick Interview Answer

Number.isNaN(value) returns true only when the supplied value is actually the numeric NaN value. The global isNaN(value) first attempts numeric coercion and then tests the result.

Detailed Explanation

Number.isNaN(value) returns true only when the supplied value is actually the numeric NaN value. The global isNaN(value) first attempts numeric coercion and then tests the result.

Because of that coercion, the global function can return true for non-numeric strings and other values that are not themselves NaN. Number.isNaN is therefore preferred when precise type-safe checking is required.

Code Example

console.log(Number.isNaN(NaN));   // true
console.log(Number.isNaN("abc")); // false

console.log(isNaN(NaN));          // true
console.log(isNaN("abc"));        // true because Number("abc") is NaN