iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

TypeWhat you get per iteration
ArrayEach item
StringEach character (handles surrogate pairs correctly)
SetEach value
Map[key, value] pairs
NodeListEach node (DOM)
GeneratorEach 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);

Test yourself

Q1. `for…of` iterates a value's…
Q2. Get [index, value] pairs in a for…of with…
Q3. Plain objects work with for…of…

Discussion

Loading…