The for...of Loop

Loop directly over the items of an array.

Syntaxfor (const item of array) { ... }

The for...of loop iterates over the values of an array (or any iterable). It is the cleanest way to visit each item.

No index needed

You get each value directly, without managing a counter or indexes.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Iterate over an array of API results to render each as a list item in the UI.
  • Loop through a Set of unique tag names to build a tag cloud component.
  • Process each character in a string to validate it against an allowed character list.

More examples

for-of over an array

Iterates directly over the array values without needing an index variable.

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

for-of with entries for index

Uses entries() with destructuring to get both the index and value in a for-of loop.

Example · js
const items = ["apple", "banana", "cherry"];
for (const [i, item] of items.entries()) {
  console.log(`${i + 1}. ${item}`);
}

for-of over a Set

Iterates over a Set of unique tags; for-of works on any iterable, not just arrays.

Example · js
const tags = new Set(["js", "css", "html", "js"]); // duplicate removed
for (const tag of tags) {
  console.log(tag);
}

Discussion

  • Be the first to comment on this lesson.
The for...of Loop — JavaScript | SoundsCode