Differences between typeof and instanceof in JavaScript

Eric picture Eric · Feb 12, 2013 · Viewed 57k times · Source

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?

Answer

Niet the Dark Absol picture Niet the Dark Absol · Feb 12, 2013

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".