Angular.js: isNumber(NaN) returns true

Created on 29 Dec 2011  路  13Comments  路  Source: angular/angular.js

NaN is supposed to be Not a number and angular.isNumber(NaN) returns true.

Most helpful comment

So today I learned that "Not A Number is number"! Damn it!

All 13 comments

right, but:

$ node
> typeof NaN
'number'

It kind of makes sense if you squint with both eyes and plug your ears.

If you deliberately use NaN in your app, you should use isNaN instead of angular.isNumber.

I'm inclined to say that the current behavior, even though a bit surprising, is consistent with how NaN is being treated in javascript. If you have some good arguments for changing the behavior please share them with us.

+1 this is consistent behavior with JS

Watch out for isNaN too, isNaN("foo") is true. So you want angular.isNumber(x) && isNaN(x)

typeof NaN

The above expression returns 'number'. But should we consider most common scenarios where 'angular.isNumber' will be called and the expected behaviour?. I would say its redundant to check for NaN most of the time.

I was expecting similar results to jQuery's jQuery.isNumeric(). NaN being a number just seems silly and though it is consistent behavior with JS, having to !isNaN(num) && angular.isNumber(num) saddens me. The documentation should probably mention that it is only comparing the typeof and reinforcing that NaN is of type "number"; returning true.

consistency aside, isn't it a logical paradox that something can be both a number and not a number?

if (!isNaN(num) && angular.isNumber(num)) { /* robots' heads explode */ }

Like @TheSharpieOne I also expected the same behavior as jQuery.isNumeric().

typeof NaN === "number" --- maybe you want to complain to TC39, although they've definitely heard all of these complaints :p

(For the benefit of others reading this -- maybe a call to Number.isFinite() is more appropriate if you want NaNs and Infinities to return false:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite )

Angular checks for not null in isObject for obvious logical reasons. Even when typeof null === 'object'. This shows that consistency with JS is not the priority but common sense.
So isNumber should check for not NaN too.

+1

If I wanted to use typeof instead of isNumber I would do so, but isNumber(NotaNumber) === true does not make any sense.

you can rewrite function
angular.isNumber

I make this code
angular.isNumber = function (num) { var n = Number(num); if (typeof (n) === 'number' && !isNaN(n)) { return true; } return false; };

So today I learned that "Not A Number is number"! Damn it!

Was this page helpful?
0 / 5 - 0 ratings