Lesson

JS Loop For Of

10 min reading
Free Course

JavaScript for...of: Clean Iteration Over Any Iterable

The 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.

Why for...of Beats forEach() in Many Cases

Unlike 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()).

Practical for...of Example

Watch 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)`);
  }
}

Common Mistakes to Avoid

  • Passing a plain object directly to 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).
  • Mutating the array length while iterating: Pushing or splicing items inside a for...of loop over the same array makes iteration hard to predict.
  • Confusing for...of with for...in: for (const x of ["a", "b"]) yields "a" and "b", whereas for...in yields "0" and "1".

Frequently Asked Questions

How does 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.

Can I use 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.

Is for...of available on document.querySelectorAll() results?

Yes, modern browsers make NodeList iterable, so for (const card of document.querySelectorAll(".card")) works directly.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum