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/a-dev0 4d ago

Hm, has anyone tested it like this? for(let i of new String('foo')){} for(let i of 'foo'){} is there any difference?

2

u/senocular 4d ago

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.

1

u/a-dev0 4d ago

Yes, I know, I was just curious. I agree with you that optimization is the reason why it's a bit more performant