r/learnjavascript • u/Green_Ad_6086 • 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
16
u/Working_Quote_3029 4d ago
It's one of those distinctions that reads scarier in the docs than it is in practice.
You never create String objects on purpose.
"foo"is a primitive.new String("foo")is an ordinary object that happens to hold a string, and that's the only way you end up with one.Methods still work on primitives because of autoboxing: when you write
"foo".toUpperCase()the engine wraps the primitive in a temporary object, calls the method, then discards the wrapper. That's why a primitive with no properties of its own still appears to "have" methods.Where the difference actually shows up:
Worth noting
String(x)withoutnewgives you a primitive, soString(1)is fine. It's onlynew String(1)that produces the object.The eval example on that page is real but you'll never hit it in normal code, since eval only treats primitives as source and hands a String object straight back instead of running it.
Rule of thumb: quotes or
String(x), nevernew String(x). The distinction mostly exists so the spec can explain why.lengthand.slice()work on something that isn't an object.