Search code examples
javascripttypesconstructordetectiontypeof

constructor vs typeof to detect type in JavaScript


In this question I did not see suggestions to use constructor.

So instead of typeof callback == "function"

I would use callback && (callback.constructor==Function).

To me it seems obvious that comparison to memory pointers is always better than comparison to strings in terms of both runtime performance and coding safety.

Why not use constructor to detect all types and forget about ugly typeof?

It works for all primitive types, functions and arrays:

undefined === undefined
null === null
[1,2,3].constructor == Array 
(1).constructor == Number
(true).constructor == Boolean
(()=>null).constructor == Function
'abc'.constructor == String
(new Date()).constructor == Date
else it's an object, where instanceof helps to detect it's parents if needed.

If string interning can be relied upon then runtime performance advantage goes away. But safe coding advantage still stays.


Solution

  • instanceof is better because it works with inherited constructors. .constructor is a mutable property on an object, so it's not a good thing to check because one can simply change it. You can't change the instanceof something.

    const x = new Date();
    console.log("Date Constructor", x.constructor);
    x.constructor = "herpderpderp";
    console.log("Date Constructor", x.constructor);