Take the 2-minute tour ×

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?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

"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)

share|improve this answer
Can you please explain what is meant by primitive value? And how then, does it have constructor property? –  Cupidvogel Dec 19 '12 at 18:30
JavaScript automatically converts primitives to String objects. Then, it should return true for console.log(a instanceof String), right? –  Cupidvogel Dec 19 '12 at 18:31
Primitive value (which can also be boolean or numbers) are simply lighter values and not instances. But the js engine makes it possible to call methods by promoting them when needed. But only when needed (that is when you need to call a method, not when you call instanceof). –  dystroy Dec 19 '12 at 18:31
This provides a pretty good explanation of the primitive vs object question: skypoetsworld.blogspot.com/2007/11/… the main punchline though is: "The difference between a primitive and a String object is when you're adding functionality to a String. You can't do it to primitives. So, if you wanted to add a function to reverse the characters in a string, you'd do something like this by adding it to the String object's prototype property --" –  Byron Dec 19 '12 at 18:32
Oh, I did not know that! Thanks! So, for both property lookup and constructor finding, it wraps up the primitive in the corresponding object? –  Cupidvogel Dec 19 '12 at 18:33
show 3 more comments

Your Answer


