Skip to content

for...of: loop over any iterable's values (ES2015)

  • What for...of does under the hood: the iterator protocol and Symbol.iterator.
  • How it handles arrays, strings, Map, Set, entries() and generators.
  • How break, return and 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...of over forEach, a classic for loop or for...in.

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.

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-100
array: B-200
string: h
string: €
string: 😀
map: A-100 4
map: B-200 0
set: new
set: sale
entries: 0 A-100
entries: 1 B-200
generator: 1
generator: 2
TypeError: order is not iterable

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

// Fragment: syntax
for (const value of iterable) statement
for (let value of iterable) statement // the binding can be reassigned in the body
for (const [key, value] of map) statement // any destructuring pattern
for (target.prop of iterable) statement // assigns to an existing reference

The 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-100
B-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 have return(), which the loop calls when it exits early.
  • Fresh binding per iteration: with let or const, 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 length on 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 a
processing a+
processing a++
[ 1, 2, 3 ]
[ 1, 2 ]

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 x
second loop y
second loop z
gen first 1

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 reader
stopping at invalid line: "oops"
close reader
total: 44.48

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

  • Using it on a plain object. {} has no Symbol.iterator, so the loop throws TypeError: ... is not iterable. Use Object.keys(), Object.values() or Object.entries().
  • Confusing it with for...in. for...in gives keys as strings; for...of gives values. See for…in.
  • Expecting to update the array through the loop variable. for (let p of prices) p *= 2 changes only the local binding. Use map, or entries() and assign prices[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 use Promise.all or a bounded pool.
  • Forgetting finally in custom generators. Early exit only helps if the generator puts its clean-up in finally.
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.

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

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.

  • for...of (ES2015) iterates values of any iterable through Symbol.iterator.
  • It supports break, continue, return and await, unlike forEach.
  • Early exit calls the iterator’s return(), so generators can clean up in finally.
  • Plain objects are not iterable; use Object.entries().
  • Strings iterate by code point, Map by [key, value] pairs.