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:
value
: The value to be tested.
Return Value:
- Returns
true
if the value isNaN
; otherwise, it returnsfalse
.
Key Characteristics:
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 returnstrue
for the actualNaN
value.Strict Check: This method only returns
true
forNaN
, making it more predictable for checking numeric values.
Example 1: Basic Usage
In these examples, both values are NaN
, so the function returns true
.
Example 2: Non-NaN Values
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:
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 usingNumber.isNaN()
.
Summary:
- The
Number.isNaN(value)
function checks if a value isNaN
without coercing the argument to a number type. - It returns
true
only for the actualNaN
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.