for...of: Clean Iteration Over Any IterableThe JavaScript for...of loop steps through the values of any iterable object, including arrays, strings, Set, Map, and DOM NodeList collections. Introduced in ES6, it gives you direct access to each element without index boilerplate.
for...of Beats forEach() in Many CasesUnlike Array.prototype.forEach(), for...of supports break, continue, return from the enclosing function, and sequential await calls inside async functions. It also works on non-array iterables such as Map, Set, and strings.
When you still need the numeric index alongside the item, call array.entries() inside for (const [index, item] of array.entries()).
for...of ExampleWatch how cleanly for...of handles arrays, entries(), and Map collections in modern JavaScript.
const fruits = ["mango", "papaya", "guava"];
for (const [index, fruit] of fruits.entries()) {
console.log(`#${index + 1}: ${fruit}`);
}
const inventory = new Map([
["notebooks", 14],
["markers", 30],
]);
for (const [item, count] of inventory) {
if (count < 20) {
console.log(`Restock needed for ${item} (${count} left)`);
}
}
for...of: Writing for (const val of { a: 1 }) throws TypeError: obj is not iterable. Wrap plain objects with Object.entries(obj) or Object.values(obj).for...of loop over the same array makes iteration hard to predict.for...of with for...in: for (const x of ["a", "b"]) yields "a" and "b", whereas for...in yields "0" and "1".for...of handle Unicode emojis in strings?for...of iterates by full Unicode code point rather than UTF-16 half-units, so emojis like "🚀" stay intact in one iteration instead of splitting in two.
await inside a for...of loop?Yes, for...of pauses cleanly at each await inside an async function, unlike forEach(), which fires all async callbacks simultaneously without waiting.
for...of available on document.querySelectorAll() results?Yes, modern browsers make NodeList iterable, so for (const card of document.querySelectorAll(".card")) works directly.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.