What is the difference between typeof and instanceof and when should one be used vs. the other?
Use instanceof
for custom types:
var ClassFirst = function () {};var ClassSecond = function () {};var instance = new ClassFirst();typeof instance; // objecttypeof instance == 'ClassFirst'; // falseinstance instanceof Object; // trueinstance instanceof ClassFirst; // trueinstance instanceof ClassSecond; // false
Use typeof
for simple built in types:
'example string' instanceof String; // falsetypeof 'example string' == 'string'; // true'example string' instanceof Object; // falsetypeof 'example string' == 'object'; // falsetrue instanceof Boolean; // falsetypeof true == 'boolean'; // true99.99 instanceof Number; // falsetypeof 99.99 == 'number'; // truefunction() {} instanceof Function; // truetypeof function() {} == 'function'; // true
Use instanceof
for complex built in types:
/regularexpression/ instanceof RegExp; // truetypeof /regularexpression/; // object[] instanceof Array; // truetypeof []; //object{} instanceof Object; // truetypeof {}; // object
And the last one is a little bit tricky:
typeof null; // object
Both are similar in functionality because they both return type information, however I personally prefer instanceof
because it's comparing actual types rather than strings. Type comparison is less prone to human error, and it's technically faster since it's comparing pointers in memory rather than doing whole string comparisons.
A good reason to use typeof is if the variable may be undefined.
alert(typeof undefinedVariable); // alerts the string "undefined"alert(undefinedVariable instanceof Object); // throws an exception
A good reason to use instanceof is if the variable may be null.
var myNullVar = null;alert(typeof myNullVar ); // alerts the string "object"alert(myNullVar instanceof Object); // alerts "false"
So really in my opinion it would depend on what type of possible data you are checking.