Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check that a number is NaN in JavaScript?

Tags:

javascript

nan

I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:

parseFloat('geoff') == NaN;  parseFloat('geoff') == Number.NaN; 
like image 275
Paul D. Waite Avatar asked Apr 16 '10 10:04

Paul D. Waite


People also ask

How do you check if a number is NaN in JS?

The Number. isNaN() method returns true if the value is NaN , and the type is a Number.

How do you test for NaN?

Check for NaN with self-equality In JavaScript, the best way to check for NaN is by checking for self-equality using either of the built-in equality operators, == or === . Because NaN is not equal to itself, NaN != NaN will always return true .

How do you check if a value is Not-a-Number in JavaScript?

isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.

Is NaN function in JavaScript?

JavaScript isNaN() Function The isNaN() function is used to check whether a given value is an illegal number or not. It returns true if value is a NaN else returns false. It is different from the Number. isNaN() Method.


2 Answers

Try this code:

isNaN(parseFloat("geoff")) 

For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?

like image 184
chiborg Avatar answered Oct 03 '22 05:10

chiborg


I just came across this technique in the book Effective JavaScript that is pretty simple:

Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:

var a = NaN; a !== a; // true   var b = "foo"; b !== b; // false   var c = undefined;  c !== c; // false  var d = {}; d !== d; // false  var e = { valueOf: "foo" };  e !== e; // false 

Didn't realize this until @allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number

like image 45
Jazzy Avatar answered Oct 03 '22 03:10

Jazzy