Created
July 29, 2019 11:43
-
-
Save maxmckenzie/44296dd52a4045dd6149e28457c7f782 to your computer and use it in GitHub Desktop.
instanceof (custom types or custom built in types) vs typeof (built in types)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment