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

For...of with Arrays

Understand how for...of loops through array elements directly, not indexes.

For...of with Arrays

You'll learn how for...of loops directly access array elements, skipping the need for index management.

The Core Idea

When you use a for...of loop with an array, JavaScript automatically gives you each element in order, one at a time. You don't deal with index numbers like 0, 1, 2 — you work directly with the values themselves.

Think of it like a conveyor belt at a factory: instead of saying "give me item #3, now give me item #4," the belt just hands you each item automatically. You grab what arrives, do something with it, and the next one comes along.

Syntax

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

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

Compare this to a traditional for loop:

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

for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

With for...of, you skip:

  • Creating an index variable (i)
  • Writing the condition (i < colors.length)
  • Incrementing the counter (i++)
  • Accessing elements with brackets (colors[i])

When It Shines

Use for...of when you need to visit every element in order and don't need the index position. It's cleaner and less error-prone than managing loop counters yourself.

Key Takeaway: for...of loops iterate directly over array values, giving you each element without requiring manual index tracking — perfect when you only care about the data, not its position.