JS Loop For Of
for…of iterates the values of any iterable — arrays, strings, Sets, Maps, NodeLists, generators. It's the modern loop you reach for first.
What's iterable
| Type | What you get per iteration |
|---|---|
| Array | Each item |
| String | Each character (handles surrogate pairs correctly) |
| Set | Each value |
| Map | [key, value] pairs |
| NodeList | Each node (DOM) |
| Generator | Each yielded value |
| Plain object | ❌ — not iterable directly; use Object.entries(obj) |
Examples
JS
for (const fruit of ["apple", "banana"]) console.log(fruit); for (const ch of "café") console.log(ch); // c a f é (4 chars, handles é) for (const [k, v] of new Map([["a", 1], ["b", 2]])) console.log(k, v); // With Object.entries for (const [key, val] of Object.entries(user)) console.log(key, val); // With index via entries() for (const [i, v] of arr.entries()) console.log(i, v);
Sequential async
JS
for (const url of urls) {
const res = await fetch(url); // awaits one at a time
console.log(await res.text());
}
// Parallel version
await Promise.all(urls.map(u => fetch(u).then(r => r.text())));
Tip:
for…of respects iteration order and supports break/continue. Array methods like forEach don't break — use for…of when you need an early exit.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Loop For Of!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Iterate the items of an array directly.
for (const item
items) console.log(item);
Two letters — modern.
Discussion
Loading…