Differences between typeof and instanceof in JavaScript

58,237

Solution 1

typeof is a construct that "returns" the primitive type of whatever you pass it.
instanceof tests to see if the right operand appears anywhere in the prototype chain of the left.

It is important to note that there is a huge difference between the string literal "abc", and the string object new String("abc"). In the latter case, typeof will return "object" instead of "string".

Solution 2

There is literal strings and there is the String class. They are separate, but they work seamlessly, i.e. you can still apply String methods to a literal string, and it will act as if the literal string was a String object instance.

If you explicitly create a String instance, it's an object, and it's an instance of the String class:

var s = new String("asdf");
console.log(typeof s);
console.log(s instanceof String);

Output:

object
true
Share:
58,237
Eric
Author by

Eric

Web developer!

Updated on February 13, 2020

Comments

  • Eric
    Eric over 4 years

    I'm working with node.js, so this could be specific to V8.

    I've always noticed some weirdness with differences between typeof and instanceof, but here is one that really bugs me:

    var foo = 'foo';
    console.log(typeof foo);
    
    Output: "string"
    
    console.log(foo instanceof String);
    
    Output: false
    

    What's going on there?