28

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?

Eric
  • 999
  • 2
  • 8
  • 23
  • 3
    In JavaScript, I believe there's a dichotomy between the primitive string type and the "object" `String` type. Most of the time they're interchangeable, apparently not for the purpose of `instanceof` checks. – millimoose Feb 12 '13 at 18:53
  • 3
    Take a look at this: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects – Waxen Feb 12 '13 at 18:54
  • Bah, should have searched SO first: http://stackoverflow.com/questions/11571923/instanceof-string-not-behaving-as-expected-in-google-apps-script/11572009#11572009 – Eric Feb 12 '13 at 18:54
  • 1
    http://stackoverflow.com/questions/203739/why-does-instanceof-return-false-for-some-literals – Nishant Jani Feb 12 '13 at 18:56
  • take a look at this one please [http://skilldrick.co.uk](http://skilldrick.co.uk/2011/09/understanding-typeof-instanceof-and-constructor-in-javascript/) – eppej Feb 12 '13 at 18:55

2 Answers2

42

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

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Where is this "huge" difference? In current NodeJS, If I do `x = 'x'; y = new String('x')`, I can treat `x` and `y` them almost interchangeably except for a small handful of operators like `typeof`, `instanceof`, `===`. `y.constructor === x.constructor` even returns true! – spinkus Mar 18 '20 at 08:14
9

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
Guffa
  • 687,336
  • 108
  • 737
  • 1,005