Course contentsShow
← JavaScript
Lesson 352 of 2,72310. LoopsFree lesson

For...of with Strings

Iterate over individual characters in a string using for...of loops.

For...of with Strings

You'll learn how to iterate over each character in a string using a for...of loop, just like you did with arrays.

The Core Idea

In JavaScript, strings are iterable—meaning you can loop through them character by character using a for...of loop. Each iteration gives you one character from the string, starting at the beginning and moving to the end.

Think of it like reading a book letter by letter: the for...of loop automatically moves from the first character to the last, letting you work with each one individually.

How It Works

let word = "hello";

for (let char of word) {
  console.log(char);
}
// Output:
// h
// e
// l
// l
// o

Each time through the loop, the variable char holds one character from the string word. You don't need to worry about indexes or string length—the loop handles all that automatically.

Practical Example

let message = "Hi!";
let count = 0;

for (let letter of message) {
  count = count + 1;
}

console.log(count); // 3

Here we're counting characters by looping through each one. This is much simpler than using a traditional for loop with indexes.

Why Use For...of with Strings?

  • Cleaner code: No need to track indexes or use bracket notation
  • Natural reading: The code reads like plain English
  • Safe: You can't accidentally go past the string's end

Key Takeaway: Use for...of loops to iterate over strings character by character—it's the simplest way to process each letter, space, or symbol in sequence.