How to Loop Through a String in JavaScript

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:

What about a pure JavaScript solution?

for (var x = 0; x < str.length; x++) {
  var c = str.charAt(x);
  console.log(c);
}

This solution is straightforward and through to be the most performant option.

Another alternative is for of which is also some ES6 sugar syntax. It’s supported by most modern browsers. 

let text = new String("abc");
for (let letter of text) {
  text += letter;
}
console.log(text);

Conceptually, it’s probably the most readable approach as its quite descriptive.

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.