Search code examples
javascriptprototypeprototypal-inheritance

Why does 'abc'.hasOwnProperty('length') == true


Please help me understand prototype inheritance in this case:

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


Solution

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