3

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

8 Comments

Can you please explain what is meant by primitive value? And how then, does it have constructor property?
JavaScript automatically converts primitives to String objects. Then, it should return true for console.log(a instanceof String), right?
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).
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 --"
Oh, I did not know that! Thanks! So, for both property lookup and constructor finding, it wraps up the primitive in the corresponding object?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.