An alternative, safer & cleaner way to compare Types in javascript
1391/11/19

I was never happy with javascript type checking using typeof and comparing the result with a string; as a small spelling error in type name can lead into false results that do not even throw a good error. After a discussion with Afshin Mehrabani (Thank you man!) we thought we can put an end to this. So here is the initial result of that discussion.

Not bad at all Huh? You may ask Is it fast enough as typeof? No, I mean not at all. Is it elegant and less error pron than comparing types with strings? Yes, and a big YES! Even you get a great error while that type is misspelled and actully does not exists. I think most of us can live with its low speed as long as we wouldn't need very faster type checking than ~ 1,782,000 checks per second!

Comments

Harry Clarke— 2014-09-12

In IE (11 at least) doesn't give functions name values, which makes breaks this method, unfortunately, in a way which can go undetected (obj.constructor.name and type.name are both undefined).
A quick check to see if type.name is undefined can allow you to use the old method when IE inevitably fails.

Any thoughts? Please leave a reply

Name:

Email:I'll use your email to show your picture using
gravatar. I hate spam too.