for...of Loop: Iterating Over Iterable ObjectsThe for...of statement (introduced in ES6) creates a loop iterating over iterable objects (Arrays, Strings, Maps, Sets, NodeLists, TypedArrays), pulling values directly without index tracking.
for...of Iterable Protocol Protocolflowchart LR
IterObj["Iterable Object (Array, Set, Map)"] --> Protocol["Calls [Symbol.iterator]()"]
Protocol --> Iterator["Returns Iterator Instance"]
Iterator --> NextVal["Yields value via .next() until done: true"]
| Loop Type | Target | What it Yields | Supports break/continue? |
|---|---|---|---|
for...of |
Iterables (Arrays, Maps, Sets, Strings) | Element Values | Yes |
for...in |
Objects | Property Keys / Names | Yes |
Array.forEach() |
Arrays | Element Values & Indices | No (Cannot break early) |
// Demonstrating for...of over Arrays, Strings, Maps, and Sets
// 1. Iterating Over Arrays
const frameworks = ["React", "Vue", "Svelte"];
console.log("--- Array Iteration ---");
for (const item of frameworks) {
console.log(`Framework: ${item}`);
}
// 2. Getting Index and Value using entries()
console.log("
--- Array Index + Value via entries() ---");
for (const [index, name] of frameworks.entries()) {
console.log(`[${index}]: ${name}`);
}
// 3. Iterating Over Strings (Unicode-aware)
console.log("
--- String Iteration ---");
for (const char of "JS🚀") {
console.log(`Char: ${char}`);
}
// 4. Iterating Over Maps
const userRoles = new Map([
["alex", "admin"],
["sarah", "editor"]
]);
console.log("
--- Map Key-Value Iteration ---");
for (const [user, role] of userRoles) {
console.log(`User: ${user} -> Role: ${role}`);
}
for...of for Clean Array Loops: for...of provides the cleanest syntax for looping through array values when early loop exit (break) is needed.for...of Fails on Plain Objects: Plain objects ({}) are NOT iterable by default and throw TypeError: obj is not iterable. Use for...of with Object.entries(obj).for await...of): for await...of allows sequential processing of asynchronous streams and Promises.Iterate over the entries of a plain object { a: 1, b: 2 } using for...of combined with Object.entries().
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.