How do you test if a value is equal to NaN in Javascript?

JavascriptFront End TechnologyObject Oriented Programming

The global NaN property in javascript is a value representing Not-A-Number. It is the returned value

  • When Math functions fail (Math.sqrt(-500))
  • When a function trying to parse a number fails (parseFloat("test"))

NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value.

To test if a value is NaN, we must use Number.isNaN method.

Example

let a = Math.sqrt(-500);
console.log(Number.isNaN(a))

Output

true

Note − isNaN() and Number.isNaN(): the former returns true if the value is currently NaN, or if it is going to be NaN after it is coerced to a number, while the latter will return true only if the value is currently NaN.

Example

isNaN('hello world');
Number.isNaN('hello world');

Output

true
false
raja
Published on 16-Sep-2019 11:16:12
Advertisements