JS: Difference between isNan() and Number.isNan()

isNaN() and Number.isNaN() are both JavaScript functions, but they behave slightly differently.

isNaN() Function:

  • The isNaN() function is a global function in JavaScript.
  • It converts the argument to a Number before checking if it is NaN.
  • It returns true if the value is NaN, and false otherwise.
  • However, it has some quirks that can lead to unexpected results. For example, it coerces non-numeric values to numbers before checking.

Example

isNaN("Hello"); // true
isNaN("123");   // false

Number.isNaN() Method:

  • The Number.isNaN() method is a static method of the Number object introduced in ECMAScript 2015 (ES6).
  • It does not perform any type coercion. It only returns true if the provided value is of the type Number and is also NaN. Otherwise, it returns false.
  • It’s more reliable for checking whether a value is NaN because it doesn’t convert non-numeric values to numbers.

Example:

Number.isNaN("Hello"); // false
Number.isNaN("123");   // false

In summary, while both isNaN() and Number.isNaN() are used to check if a value is NaN, Number.isNaN() is more reliable and is generally recommended for checking NaN values in modern JavaScript code due to its lack of type coercion.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *