Reputation: 5153
I used to think that both assignments a = "foo"
and a = new String('foo')
are the same things. But with the former declaration, console.log(a instanceof Object)
or console.log(a instanceof String)
returns false
, while it returns the expected true
for the latter.
This seems weird for two reasons. Firstly, even with the normal declaration a = 'foo'
, all string methods work on it, suggesting that it has inherited from String
object. And secondly, a.constructor
returns String
.
Can anybody explain what's going on?
Upvotes: 3
Views: 55
Reputation: 382130
"foo"
is a primitive literal.
But new String("foo")
is an instance of the class String.
You can call methods on the primitive value because
JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.
(from the MDN)
Upvotes: 3