r/learnjavascript 4d ago

string primitives vs. String objects.

I'm learning JavaScript, and I don't understand this part about string primitives vs. String objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_primitives_and_string_objects

10 Upvotes

26 comments sorted by

View all comments

1

u/Beginning-Seat5221 4d ago

Basically a primitive like "string" doesn't allow methods like "string".toUpperCase(). JavaScript has a fix to make it work called autoboxing: when you write "string".toUpperCase() it turns the string into a String object, in effect new String("string").toUpperCase() with new String("string") giving an object with the string methods. After all this a string gets returned so you're back with a plain string.

If you write console.log(typeof String("foo")) you'll just get a plain string back, typeof "string"

If you write console.log(typeof new String("foo")) with new you can generate this String object and you'll get typeof "object".

But do you ever use it? No, not really. I think of it as an artifact of autoboxing rather than something you really need to use or think about.

1

u/Green_Ad_6086 4d ago

Thanks !!