Course contentsShow
← JavaScript
Lesson 190 of 2,7235. StringsFree lesson

Iterating Strings with For...of

Use for...of loops to iterate over strings by code points, correctly handling multi-byte characters and emoji.

Iterating Strings with For...of

You'll learn: How to use for...of loops to correctly iterate over strings character-by-character, even when they contain emoji and special Unicode characters.

The Problem with Traditional Loops

Remember how length and bracket notation can't see beyond code units? A string like "👍" has a length of 2, not 1. Traditional for loops that iterate by index will split surrogate pairs apart, giving you broken characters.

The For...of Solution

The for...of loop is smarter—it iterates by code points, not code units. This means it automatically handles multi-byte characters correctly:

const text = "Hi👋";

for (const char of text) {
  console.log(char);
}
// Output:
// H
// i
// 👋

Notice how the emoji 👋 appears as a single character, not split into two pieces.

How It Works

Think of for...of as walking through the string with "Unicode-aware vision." It sees complete characters, including:

  • Regular ASCII letters
  • Accented characters
  • Emoji
  • Any multi-byte Unicode character
const greeting = "Héllo🌍";

for (const char of greeting) {
  console.log(char);
}
// Output: H é l l o 🌍
// Each on its own line, all intact

When to Use It

Whenever you need to process a string character-by-character and you want to treat emoji, symbols, and international text correctly, reach for for...of. It's the modern, safe way to iterate strings.

Key Takeaway: Use for...of to iterate over strings by complete code points, ensuring emoji and multi-byte characters are handled correctly without manual surrogate pair management.