JavaScript Number.isNaN(value) function


The Number.isNaN(value) function in JavaScript is a static method that determines whether the provided value is NaN (Not-a-Number). This method is part of the Number object and provides a reliable way to check for NaN without type coercion.

Syntax:

Number.isNaN(value)
  • value: The value to be tested.

Return Value:

  • Returns true if the value is NaN; otherwise, it returns false.

Key Characteristics:

  1. No Type Coercion: Unlike the global isNaN() function, which coerces the argument to a number before checking, Number.isNaN() does not perform type coercion. It only returns true for the actual NaN value.

  2. Strict Check: This method only returns true for NaN, making it more predictable for checking numeric values.

Example 1: Basic Usage

console.log(Number.isNaN(NaN)); // true console.log(Number.isNaN(Number.NaN)); // true

In these examples, both values are NaN, so the function returns true.

Example 2: Non-NaN Values

console.log(Number.isNaN(123)); // false console.log(Number.isNaN("Hello")); // false console.log(Number.isNaN(undefined)); // false

In these cases, 123, "Hello", and undefined are not NaN, resulting in false.

Example 3: Type Coercion with isNaN

To illustrate the difference between Number.isNaN() and the global isNaN() function:

console.log(isNaN("Hello")); // true (coerced to NaN) console.log(Number.isNaN("Hello")); // false (not NaN)

Here, the global isNaN() function coerces the string "Hello" into NaN, while Number.isNaN() does not.

Example 4: Special Cases

  • NaN in Calculations: When an operation results in NaN, this can be checked using Number.isNaN().
console.log(Number.isNaN(0 / 0)); // true console.log(Number.isNaN(Math.sqrt(-1)); // true

Summary:

  • The Number.isNaN(value) function checks if a value is NaN without coercing the argument to a number type.
  • It returns true only for the actual NaN value, making it a reliable method for determining whether a value is Not-a-Number.
  • This method is useful for validating numeric computations and ensuring that operations produce valid results, especially when dealing with potentially invalid calculations.