Tuesday, May 19, 2009

ExtendScript: instanceof Number

var xyz = 123.45;
alert(xyz instanceof Number);

Always false. Not very intuitive at first.

Searching for ExtendScript instanceof Number didn't help, but searching for Javascript instanceof Number did.

Unfortunately, the short of it is that we have to resort to the slowness of string comparisons. C'mon - I thought this was the 21st century!

var xyz = 123.45;
alert(typeof xyz == 'number');

But there are situations where instanceof Number DOES work :

var xyz = new Number(123.45);
alert(xyz instanceof Number); // true

... and in such instances, the typeof trick DOESN'T work :

var xyz = new Number(123.45);
alert(xyz instanceof Number); // true
alert(typeof xyz == 'number'); // false

There is a reason for it, and when you understand the reason, it makes sense enough, but it does prove that javascript and all its derivatives are a little idiosyncratic and obscure at times.

For more info :

StackOverflow - why does instanceof return false for some literals?

More technical info (hands-on) about javascript and instanceof

Thanks to the two articles I just listed! They helped solve for me what was seeming a great (and annoying) mystery.

No comments: