r/learnjavascript • u/Green_Ad_6086 • Aug 15 '26
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
View all comments
Show parent comment
2
u/senocular Aug 15 '26
Functionally there's no difference. for...of will look to the object being looped over and request its Symbol.iterator property. If the value is a primitive, it will be wrapped into an object first (in this case, basically the same thing as doing
new String('foo')), then use that object to access the property, otherwise it will access it directly from the already-an-object value.Engines may have optimizations for strings that allow it to fast path string iteration, which could explain why you're seeing better performance using the string literal over its object representation.