2

Possible Duplicate:
Why does instanceof return false for some literals?

If I do...

[] instanceof Array;

...it returns true although I haven't used new Array().

But if I do...

"" instanceof String;

...it returns false because I haven't used new String().

Why? I understand that [] is a language construct for creating arrays and "" is a language construct for creating strings. So I don't understand why one returns true and the other returns false.

Moreover, all of the following codes return true:

[] instanceof Array; /* true */
Array() instanceof Array; /* true */
new Array() instanceof Array; /* true */

But with strings:

"" instanceof String; /* false */
String() instanceof String; /* false */
new String() instanceof String; /* true */

Shouldn't String() instanceof String return true too?

Edit:

I have made a new question (spin-off of this one): Easy way to check if a variable is a string?

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • It _is_ a bit confusing. If you want to test if `something` is a string you can do `typeof something === "string"`. You'll find `typeof "" === "string"` will be `true`. – nnnnnn Sep 03 '12 at 22:28
  • "Should" is a tricky word; do you mean "should" as in "JavaScript is intrinsically broken," or "should" as in "it doesn't meet with my expectations", or "should" as in something said it should, but it doesn't? In any case, strings are a value type in JS; see [this answer](http://stackoverflow.com/questions/2051833/difference-between-the-javascript-string-type-and-string-object) for more details. – Dave Newton Sep 03 '12 at 22:29
  • A `string` value is not a `String` value although it shares the `[[prototype]]` .. (same for `number` vs. `Number`, etc.) –  Sep 03 '12 at 22:29
  • 1
    @pst I don't think that's true - what happens is that a string constant is promoted to a String object when necessary - like when it's used as the left operand of the `.` operator. String constants and numbers don't have a prototype because they're not objects. – Pointy Sep 03 '12 at 22:37
  • @nnnnnn But your code doesn't work with `new String()`. Must I do `typeof abc === "string" || abc instanceof String` each time I want to check if a variable `abc` is a string? – Oriol Sep 03 '12 at 22:46
  • Yes, sorry, but why would you ever actually use `new String()`? – nnnnnn Sep 03 '12 at 23:00
  • @Pointy Given `String.prototype.me = function () { return this; }`, then `"".me() === ""` agrees with your last comment as `typeof "".me()` yields "object" (in FF14), but I am not well versed in this aspected of the ECMAScript specification. IIRC I thought this behavior was a "bug" of an implementation, from a vague memory of a previous SO post .. –  Sep 04 '12 at 02:24

0 Answers0