Menu

How to Loop Through a String in JavaScript

23 March 2020

From time to time we find ourselves reaching for a JavaScript method that’s not particularly obvious. We rarely try and loop through primitive types in types in our day to day programming. However, there are still many niche use cases for iterating through a string value.

So, how exactly do you loop through a string in JavaScript?

Let’s say we have a string like so:

const text = new String("Tommy")

Using the latest in ES6 syntax:

[...text].forEach(char => console.log(char))

Notice how we are spreading text into an array and then using forEach as you would for any other array type.

But how exactly is that possible, how can you spread a string value? Well, the actual type of a string is an object.

typeof new String("abc")
// outputs: "object"

This can be a little confusing, however, if you have ever accessed a string you’ll notice it has a whole host of methods and properties: