How do you check that a number is NaN in JavaScript?
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?
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
Use this code:
isNaN('geoff');
See isNaN()
docs on MDN.
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
As far as a value of type Number is to be tested whether it is a NaN
or not, the global function isNaN
will do the work
isNaN(any-Number);
For a generic approach which works for all the types in JS, we can use any of the following:
For ECMAScript-5 Users:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
For people using ECMAScript-6:
#2
Number.isNaN(x);
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
please check This Answer for more details.
As of ES6, Object.is(..)
is a new utility that can be used to test two values for absolute equality:
var a = 3 / 'bar';
Object.is(a, NaN); // true