2

Why does:

var a = "string";
console.log("length" in a);

Gives error

var b = new String("string");
console.log("length" in b);

Gives true.

a has property length just as same as b. a typeof is string but it's also an object with its own properties. MDN says:

JavaScript automatically converts primitives to String objects , so that it's possible to use String object methods for primitive strings.

What's wrong?

  • "*a typeof is string but it's also an object with it's own properties.*" - well no. – Bergi Mar 26 '17 at 13:50
  • 1
    The implicit context is omitted in your quote: "JavaScript automatically converts primitives to String objects *[when accessing properties]*". The `in` operator does not access a property. – Bergi Mar 26 '17 at 13:51

2 Answers2

1

The in keyword works only on objects.

var a = 'foo';
var b = new String(a);

console.log(typeof a);  // "string"
console.log(typeof b);  // "object"

Read the documentation on the distinction between string primitives and string objects

The following code will automatically convert the primitive to an object upon accessing a property, in this case length.

console.log("string".length);
Xorifelse
  • 7,878
  • 1
  • 27
  • 38
0

b is an object of type String, while a is not, it is a string. If you try a.isPrototypeOf(String) it should output false

kkica
  • 4,034
  • 1
  • 20
  • 40