Grzegorz
Grzegorz

Reputation: 3608

Javascript isNAN returns false if checking Object?

I have a script which behaves strangely.

console.log (typeof button);
console.log ('IsNAN ' + isNaN(button));
console.log ('isNumeric ' + jQuery.isNumeric(button));
console.log ();

when button is an object, isNaN should return true; Because object isNaN. However console shows differently:

object
IsNAN false // should be true!
isNumeric false

Why is that?

Edit: The Problematic script is http://flesler-plugins.googlecode.com/files/jquery.serialScroll-1.2.2.js

Line 126 @ function jump( e, button ).

Upvotes: 1

Views: 654

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074555

IsNAN false // should be true!

Not necessarily. :-) isNaN is only true if the argument to it (converted to a Number if necesssary) is NaN.

Depending on what the object is, it may or may not be NaN when converted to a Number. It depends on what happens when the object is converted to its primitive value. null, for instance, converts to 0. In many, many other cases conversion to primitive involves turning it into a string (arrays, for instance), and the default toString of some objects may return something that can be converted to a non-NaN Number.

Examples of non-NaN objects:

// null
console.log(Number(null));          // 0

// an array (which becomes "23" when converted to primitive, because
// arrays do `join` for `toString`; then the "23" becomes 23)
console.log(Number([23]));          // 23

// another object implementing toString or valueOf in a way that returns
// something convertable to a non-NaN number
console.log(Number(new Foo("47"))); // 47

...where Foo is:

function Foo(value) {
    this.value = value;
}
Foo.prototype.toString = function() {
    return this.value;
};

(In the above, toString could be valueOf as well.)

Upvotes: 4

Bay73
Bay73

Reputation: 126

I think your variable button is equal to null.

typeof(null) == 'object'

isNaN(null) == false

Upvotes: 0

harun
harun

Reputation: 1919

isNaN() called with a null object is expected to be false.

If your object is not null and cannot be converted to a number then it will return true.

Upvotes: 2

Related Questions