sliptype
sliptype

Reputation: 2974

Why does a string literal value have properties according to `hasOwnProperty`, but not according to the `in` operator?

Please help me understand prototype inheritance in this case:

Why does 'abc'.hasOwnProperty('length') return true but 'length' in 'abc' throws an error?

Upvotes: 3

Views: 244

Answers (1)

Pointy
Pointy

Reputation: 413966

The expression 'abc'.hasOwnProperty('length') is interpreted by JavaScript as

(new String('abc')).hasOwnProperty('length')

Every (capital-S) String instance has its own length property, which gives the length of the string.

JavaScript (lower-case s) string instances are primitives and do not have any properties at all. The use of a string primitive as the left-hand side of the . operator causes the string primitive to be implicitly wrapped in a String object (at least conceptually; the runtime doesn't really have to instantiate a transient object) and that's where the .length property comes from.

The expression length in 'abc' throws an exception because there's no implicit promotion of the primitive 'abc' to a String instance with the in operator. Thus since a primitive cannot have any properties, and the concept makes no sense, it's an exception.

Upvotes: 8

Related Questions