The for...of Loop
Loop directly over the items of an array.
Syntax
for (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
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.
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.
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.
const tags = new Set(["js", "css", "html", "js"]); // duplicate removed
for (const tag of tags) {
console.log(tag);
}
Discussion