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

Introduction to For...of Loops

Learn the for...of syntax for iterating over iterable objects like arrays and strings.

Introduction to For...of Loops

You'll learn a cleaner, more readable way to loop through arrays and strings without managing index variables.

What Is For...of?

The for...of loop is a modern syntax introduced in ES6 that lets you iterate directly over the values in an array or string, rather than working with indices. Instead of writing for (let i = 0; i < arr.length; i++) and then accessing arr[i], you can simply say "for each value of this array, do something."

Think of it like this: traditional for loops are like navigating a library by shelf numbers—you ask for "book at position 3, then position 4..." A for...of loop is like having someone hand you each book directly, one at a time, without you needing to track positions.

Basic Syntax

const colors = ['red', 'green', 'blue'];

for (let color of colors) {
  console.log(color);
}
// Logs: red, green, blue

Notice there's no i, no colors[i], and no i < colors.length. The loop variable (color) automatically takes on each value from the array, one per iteration.

Works with Strings Too

const word = 'hello';

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

Each character becomes the loop variable automatically.

When to Use For...of

Use for...of when you need the values themselves and don't care about the index position. It's cleaner and less error-prone than traditional for loops because there's no index arithmetic to mess up.

Key Takeaway: The for...of loop iterates directly over values in arrays and strings, eliminating the need for manual index management and making your code more readable.