When does JS create an object wrapper for a string?

Viewed 69

Symbol.iterator in 'retularString' // error right-hand side of in sould be an object

Symbol.iterator in new String() // true

Does that mean JS creates object wrappers for strings only when it calls methods / or accesses corresponding properties on them like 'string'.toUppercase() / 'string'.length?

1 Answers

Does that mean JS creates object wrappers for strings only when it calls methods / or accesses corresponding properties on them like 'string'.toUppercase() / 'string'.length?

Yes.

When you have a string declared as var foo = 'foo' its type is the primitive string, having no properties inherently, but when you try and access a property on it, the primitive is wrapped momentarily in the String object through a process called implicit coercion.

See this article for a full explanation of coercion in JavaScript.

Related