r/learnjavascript • • Oct 04 '26

Any 'inbuilt' way to iterate over string - with access to index AND option to break?

I've been trying to learn more about iterators - but it doesn't seem like there is a string equivalent of .entries()? myStr[Symbol.iterator].forEach() gives the index and value - but no option to break 😞

For veryyyyyy long strings is my best option for loops? Splitting to create an array? Writing a separate generator function? (assume I only need a single char/index per loop)

Thanks!

Edit - thanks to u/Psionatix for guiding me to Object.entries(myStr), which led me to Array.prototype.entries.call(myStr) - which has the benefit of returning the indexes as integers (vs strings in Object.entries()) Performance is also close enough to for loop for my purposes 🎉

15 Upvotes

27 comments sorted by

View all comments

Show parent comment

1

u/chikamakaleyley helpful Oct 04 '26

any thoughts on using .charAt(i) vs [i] here?

personally here i lean towards .charAt() just cuz i think the optics makes it obvious at a glance that we're working w a string. Even though str[i] is valid, my brain says to me "we're given these convenient methods for strings, lets use them'

1

u/jhartikainen Oct 04 '26

Historically function calls have been noticeably more expensive in some cases than not doing function calls, so I would have said use the index syntax - but today it probably doesn't make any real difference. I would probably use the index syntax myself because it's less typing :)

I have a vague recollection that the index syntax didn't work for strings way back in the day, which is why charAt exists, but I might be misremembering this.

1

u/chikamakaleyley helpful Oct 04 '26

ah no that sounds valid but yeah if we're dealing with a few words like parsing titles of something

Same i had to look it up, ES5 is the spec, didn't work in IE7, good riddance