Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between typeof and instanceof and when should one be used vs. the other?

In my particular case:

callback instanceof Function 

or

typeof callback == "function" 

does it even matter, what's the difference?

Additional Resource:

JavaScript-Garden typeof vs instanceof

like image 806
farinspace Avatar asked May 22 '09 19:05

farinspace


1 Answers

Use instanceof for custom types:

var ClassFirst = function () {}; var ClassSecond = function () {}; var instance = new ClassFirst(); typeof instance; // object typeof instance == 'ClassFirst'; // false instance instanceof Object; // true instance instanceof ClassFirst; // true instance instanceof ClassSecond; // false  

Use typeof for simple built in types:

'example string' instanceof String; // false typeof 'example string' == 'string'; // true  'example string' instanceof Object; // false typeof 'example string' == 'object'; // false  true instanceof Boolean; // false typeof true == 'boolean'; // true  99.99 instanceof Number; // false typeof 99.99 == 'number'; // true  function() {} instanceof Function; // true typeof function() {} == 'function'; // true 

Use instanceof for complex built in types:

/regularexpression/ instanceof RegExp; // true typeof /regularexpression/; // object  [] instanceof Array; // true typeof []; //object  {} instanceof Object; // true typeof {}; // object 

And the last one is a little bit tricky:

typeof null; // object 
like image 73
Szymon Wygnański Avatar answered Sep 20 '22 17:09

Szymon Wygnański