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.

function assertType(obj, type) {
    return ===

And now let's test it:

assertType("test", String); //true
assertType(1, String); //false
assertType(1, Number); //true
function Book(){};
function Desk(){};
var book = new Book();
assertType(book, Book); //true
assertType(book, Desk); //false

assertType([], Array); //true
assertType(function(){}, Function); //true

And compare it with the traditional "typeof" method. as you may know it has shortcomings with objects and arrays

typeof "test" === "string"; //true
typeof 1 === "string"; //false
typeof 1 === "number"; //true
typeof book === "object"; //true. but we can not compare it with its constructor type. bad!

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!

Back to home

I'm Arash Milani, hacker, avid reader, happiness ninja.
@narmand is our teams's lab to expriment awsome things in it.

I write and talk about hacking, developing web apps, teamwork and designing for better user experience.

You can always contact me via me[at] email address.