4.8 For...of Loops

As mentioned at the end of the previous lesson, ES6 introduced a new way to iterate over collections: the for...of loop. It looks almost identical to for...in but uses the keyword of instead of in. The difference is fundamental — for...of gives you the element directly, not its index.

Here is an example with a colours array:

const colors = ["red", "green", "blue"];
for (let color of colors) {
  console.log(color);
}

With for...of, there is no index to manage and no bracket notation needed to read the element. At each iteration, color already holds the current value of the array. When you save the changes you see red, green and blue printed on the console, one per line.

When to use which loop

  • for...in — iterates over the properties of an object (keys).
  • for...of — iterates over the elements of an iterable like an array.

That's the short demo on for...of loops. They are the cleanest way to walk an array in modern JavaScript — see you in the next video.

Summary

This lesson introduces for...of loops, a modern ES6+ syntax for iterating over array elements. Unlike traditional for loops that require index management, for...of provides direct access to each element on every iteration. The lesson also differentiates for...of from for...in: for...in iterates over object properties while for...of iterates over array elements or items.

Key points

  • for...of is a new looping syntax from ES6+ designed to iterate directly over array elements
  • Basic syntax: for (let element of array) { console.log(element); } — no index management needed
  • Key difference: for...in loops over object properties; for...of loops over array elements
  • Each iteration assigns the current element directly to the loop variable (e.g., 'colour') without manual index access
  • Example demonstrated: iterating over a colors array outputs each color (red, green, blue) naturally

FAQ

What is the main difference between for...in and for...of loops?

for...in is used to iterate over the properties of an object, while for...of is used to iterate over the elements of an array. With for...of, you get each element directly without needing to manage an index.

Do I need to manually manage the index with for...of loops?

No. The for...of loop automatically provides each element of the array at every iteration, so you don't need to access or track the index yourself.

What happens at each iteration of a for...of loop?

At each iteration, the loop variable (e.g., 'colour') is assigned one element from the array, allowing you to work with that element directly in the loop body.