for...of: loop over any iterable's values (ES2015)
What you’ll learn
Section titled “What you’ll learn”- What
for...ofdoes under the hood: the iterator protocol andSymbol.iterator. - How it handles arrays, strings,
Map,Set,entries()and generators. - How
break,returnand exceptions close an iterator, and which iterators can be resumed. - Why plain objects are not iterable and what to use instead.
- When to choose
for...ofoverforEach, a classicforloop orfor...in.
Summary
Section titled “Summary”TL;DR: for (const value of iterable) asks iterable[Symbol.iterator]() for an iterator and runs the body once per value until the iterator reports done. It works with every built-in collection, strings, generators, DOM collections such as NodeList, and any object you make iterable. Unlike forEach, the body can break, continue, return and await.
It was added in ECMAScript 2015 (ES6) together with iterators, generators, Map and Set.
The problem it solves
Section titled “The problem it solves”Before ES2015 every collection had its own loop: an index-based for for arrays, for...in for objects, callbacks for library collections. Index loops over strings split emoji into UTF-16 halves, and forEach (ES5) cannot stop early. for...of gives one loop for anything that produces a sequence of values.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The outputs shown were produced with Node.js 22.23.
const skus = ['A-100', 'B-200'];for (const sku of skus) console.log('array:', sku);for (const ch of 'h€😀') console.log('string:', ch);const stock = new Map([['A-100', 4], ['B-200', 0]]);for (const [sku, qty] of stock) console.log('map:', sku, qty);for (const tag of new Set(['new', 'sale', 'new'])) console.log('set:', tag);for (const [i, sku] of skus.entries()) console.log('entries:', i, sku);function* ids() { yield 1; yield 2; }for (const id of ids()) console.log('generator:', id);try { const order = { id: 7 }; for (const x of order) console.log(x);} catch (e) { console.log(e.constructor.name + ':', e.message); }Output:
array: A-100array: B-200string: hstring: €string: 😀map: A-100 4map: B-200 0set: newset: saleentries: 0 A-100entries: 1 B-200generator: 1generator: 2TypeError: order is not iterableThe string loop yields whole code points, so the emoji arrives as one value. Map yields [key, value] pairs that destructure directly, and entries() gives you the index when you need it.
How it works
Section titled “How it works”// Fragment: syntaxfor (const value of iterable) statementfor (let value of iterable) statement // the binding can be reassigned in the bodyfor (const [key, value] of map) statement // any destructuring patternfor (target.prop of iterable) statement // assigns to an existing referenceThe loop is shorthand for this protocol:
// What for...of does under the hood, for one iterable.const iterable = ['A-100', 'B-200'];const iterator = iterable[Symbol.iterator]();let step;while (!(step = iterator.next()).done) { console.log(step.value);}Output:
A-100B-200- Iterable: an object with a
[Symbol.iterator]()method that returns an iterator. Arrays, strings, typed arrays,Map,Set,arguments, generator objects and DOM collections qualify. Plain objects do not. - Iterator: an object with
next()returning{ value, done }. It may also havereturn(), which the loop calls when it exits early. - Fresh binding per iteration: with
letorconst, each pass has its own variable, so closures capture the right value. Reassigning the loop variable never changes the source. - Live sequences: array iterators read
lengthon every step, so items pushed during the loop are visited.
const queue = ['a'];let n = 0;for (const item of queue) { console.log('processing', item); if (n++ < 2) queue.push(item + '+');}const callbacks = [];for (const id of [1, 2, 3]) callbacks.push(() => id);console.log(callbacks.map((f) => f()));const prices = [1, 2];for (let p of prices) p *= 2;console.log(prices);Output:
processing aprocessing a+processing a++[ 1, 2, 3 ][ 1, 2 ]Early exit closes the iterator
Section titled “Early exit closes the iterator”When the body exits through break, return, throw, or a continue that targets an outer loop, for...of calls the iterator’s return() method if it has one. For a generator that runs its finally blocks, which is how you release resources. Normal completion (the iterator says done) does not call return().
Not every iterator has return(). Array iterators do not, so a half-consumed array iterator can be resumed, while a generator is finished after break:
const it = ['x', 'y', 'z'][Symbol.iterator]();for (const v of it) { console.log('first loop', v); break; }for (const v of it) console.log('second loop', v);function* gen() { yield 1; yield 2; yield 3; }const g = gen();for (const v of g) { console.log('gen first', v); break; }for (const v of g) console.log('gen second', v);Output:
first loop xsecond loop ysecond loop zgen first 1Realistic example
Section titled “Realistic example”OrdersPortal imports order lines from a CSV export. The reader is a generator that must release its source when the import stops early, whatever the reason.
function* readLines(lines) { console.log('open reader'); try { for (const line of lines) yield line; } finally { console.log('close reader'); // runs on break, return or throw }}
const csv = ['A-100,2,9.99', 'B-200,1,24.50', 'oops', 'C-300,5,1.00'];let total = 0;for (const line of readLines(csv)) { const [sku, qty, price] = line.split(','); if (price === undefined) { console.log(`stopping at invalid line: "${line}"`); break; } total += Number(qty) * Number(price);}console.log('total:', total.toFixed(2));Output:
open readerstopping at invalid line: "oops"close readertotal: 44.48The break triggers the generator’s return(), which runs the finally block. With forEach you could not stop at the invalid line without throwing. When the lines come from a file or network stream, switch to for await...of, which follows the same closing rules.
Common mistakes
Section titled “Common mistakes”- Using it on a plain object.
{}has noSymbol.iterator, so the loop throwsTypeError: ... is not iterable. UseObject.keys(),Object.values()orObject.entries(). - Confusing it with
for...in.for...ingives keys as strings;for...ofgives values. See for…in. - Expecting to update the array through the loop variable.
for (let p of prices) p *= 2changes only the local binding. Usemap, orentries()and assignprices[i]. - Iterating a one-shot iterator twice. Generators and most iterators are consumed by the first loop. Keep the iterable (the array or a generator function) and ask it for a fresh iterator.
- Pushing to the array you are looping over without a limit. Array iteration is live, so unconditional pushes never end.
- Awaiting each item when the work is independent.
for (const id of ids) await load(id)runs one request at a time. That is right for ordered or rate-limited work; for parallel work usePromise.allor a bounded pool. - Forgetting
finallyin custom generators. Early exit only helps if the generator puts its clean-up infinally.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Best choice |
|---|---|
Values of an array, string, Map, Set or generator, with break or await |
for...of |
| Index and value together | for (const [i, v] of arr.entries()) |
| Plain object keys and values | for (const [k, v] of Object.entries(obj)) |
| Transform or filter into a new array | map, filter, or iterator helpers on iterators |
| Tight numeric loop, stepping backward or by two | classic for (let i = 0; ...) |
| Inherited enumerable keys | for...in |
| Values that arrive asynchronously | for await...of |
forEach remains fine for a short side effect when you never need to stop early, but it does not wait for async callbacks; for...of with await does.
Compatibility
Section titled “Compatibility”According to MDN’s compatibility data, for...of is supported in Chrome 38, Edge 12, Firefox 13, Safari 7 and Node.js 0.12; iterator closing on early exit arrived later (Chrome 51, Edge 14, Firefox 53, Safari 7, Node.js 6.5). Deno and Bun support it from 1.0. Internet Explorer never did. For ES5 targets, transpilers convert for...of to an index loop (which works only on arrays) or to explicit iterator calls (which need Symbol and iterator polyfills).
Interview questions
Section titled “Interview questions”1. What makes an object usable in for...of?
It must be iterable: it needs a [Symbol.iterator]() method that returns an iterator, an object whose next() returns { value, done }. The easiest way to write one is a generator method: *[Symbol.iterator]() { yield* this.items; }.
2. What happens to the iterator when you break out of a for...of loop?
The loop calls the iterator’s return() method, if it exists, so it can clean up. For a generator, return() resumes it as if a return statement ran at the paused yield, so its finally blocks run and the generator is finished. Array iterators have no return(), so they can be resumed later.
3. Why prefer for...of over forEach with async code?
forEach calls the callback and ignores the promise it returns, so the loop finishes before the work does and errors become unhandled rejections. In an async function, for (const x of xs) await work(x) processes items in sequence, propagates errors to the surrounding try, and can break.
4. Senior scenario: a report generator loops over millions of database rows with for...of on an array built by fetching everything first. Memory spikes. What do you change?
Stop materializing the array. Expose the rows as an iterable that pulls batches, a sync generator over a cursor or, since database drivers are asynchronous, an async generator consumed with for await...of. Put cursor clean-up in finally so break and errors release the connection, and keep the loop body streaming its output instead of accumulating results. The loop code barely changes, which is the point of the iteration protocol.
Key takeaways
Section titled “Key takeaways”for...of(ES2015) iterates values of any iterable throughSymbol.iterator.- It supports
break,continue,returnandawait, unlikeforEach. - Early exit calls the iterator’s
return(), so generators can clean up infinally. - Plain objects are not iterable; use
Object.entries(). - Strings iterate by code point,
Mapby[key, value]pairs.
Related pages
Section titled “Related pages”- for…in: the key loop for objects, and why it is wrong for arrays.
- Async iteration:
for await...ofand async generators. - Iterators and iterables: the protocol in depth.
- Generators: the simplest way to write an iterable.
- Map and Set: collections designed for
for...of. - Destructuring: unpacking
[key, value]pairs in the loop head. - Symbol: where
Symbol.iteratorcomes from.