Sub topic 6
for...of: Walking the Values of an Iterable
This chapter assumes you know let and const, can read and write array and object literals, and are comfortable with arrow functions. The previous chapters covered for...in, which hands you property keys. This chapter covers for...of, which hands you values, and the syntax rules and common errors that go with it.
The basic shape
A for...of loop takes an iterable and runs its body once for each value the iterable produces. An iterable is any object that knows how to give out its values one at a time. Arrays, strings, Maps and Sets are iterable. Plain objects are not.
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// red
// green
// blueThe head of the loop has three parts:
- A declaration or assignment target (
const color) that receives each value. - The keyword
of. - An expression (
colors) that must evaluate to an iterable.
You get the element itself, not its index, and you never write colors[i]. That is the main difference from for...in, which would give you the strings '0', '1' and '2'.
Choosing the loop variable declaration
const is the usual choice
Each iteration gets a fresh binding, so const works even though the variable holds a different value on every pass. Use const unless you have a reason to reassign the variable inside the body.
for (const n of [1, 2]) {
try {
n = n * 2;
} catch (err) {
console.log(err.name); // TypeError
}
}Reassigning a const loop variable throws a TypeError at runtime. If you need a modified value, create a new variable (const doubled = n * 2) or declare the loop variable with let.
let when you reassign inside the body
for (let word of [' trim me ', ' and me']) {
word = word.trim();
console.log(`[${word}]`);
}
// [trim me]
// [and me]Reassigning word changes only the local binding. The original array is not modified.
var and existing targets
var also works, but it creates one function-scoped binding shared by every iteration. A later chapter on closures shows why that matters. You can also leave out the declaration and assign to a variable or property you already have:
let last;
for (last of [1, 2, 3]) {
// body intentionally empty
}
console.log(last); // 3
const box = {};
for (box.value of ['a', 'b']) {}
console.log(box.value); // 'b'This form is rare. It helps when you need the final value after the loop ends, but a declared variable plus a separate assignment is usually clearer.
The iterable expression is evaluated once
The expression after of runs one time, before the first iteration. It is not re-evaluated on each pass, unlike the condition in a classic for loop.
let calls = 0;
function getItems() {
calls++;
return ['x', 'y', 'z'];
}
for (const item of getItems()) {
console.log(item);
}
console.log('calls:', calls); // calls: 1So you can put a function call or a computed expression such as list.filter(Boolean) directly in the loop head without paying for it on each iteration.
What happens with non-iterables
If the expression is not iterable, the loop throws a TypeError before the body runs even once. The usual mistakes are passing a plain object, null or undefined.
const attempts = [{ a: 1 }, null, undefined, 42];
for (const value of attempts) {
try {
for (const inner of value) {
console.log(inner);
}
} catch (err) {
console.log(err.constructor.name, '-', err.message);
}
}
// TypeError - value is not iterable
// TypeError - value is not iterable (wording varies by engine)
// TypeError - value is not iterable
// TypeError - value is not iterableThe exact message depends on the engine. V8, used by Chrome and Node.js, says something like value is not iterable. A later chapter shows how to loop over plain objects with Object.entries. Another explains the Symbol.iterator method that decides whether something is iterable at all.
Arrays: holes and extra properties
for...of on an array visits indices 0 through length - 1 in order. That has two consequences that surprise people coming from other loops.
First, holes in a sparse array appear as undefined. A hole is an index that was never assigned. forEach skips holes, but for...of does not:
const sparse = [1, , 3];
for (const v of sparse) {
console.log(v);
}
// 1
// undefined
// 3
sparse.forEach(v => console.log(v));
// 1
// 3Second, non-index properties are ignored. If someone attaches arr.label = 'x', for...of never shows it, while for...in does. A later chapter covers this in detail.
for...of compared with neighbouring loops
| Loop | Each iteration gives you | Works on plain objects | Visits array holes | Supports break/continue |
|---|---|---|---|---|
| `for (let i = 0; ...)` | whatever you index | only with manual keys | yes, as `undefined` | yes |
| `for...in` | string property keys | yes | no | yes |
| `for...of` | values from the iterable | no, throws TypeError | yes, as `undefined` | yes |
| `arr.forEach(fn)` | value, index, array | no | no | no |
The last column matters in practice. Inside for...of you can use break, continue and return from the enclosing function. Inside a forEach callback, return only ends that one callback call. A later chapter covers early exit.
Common errors
- Writing
inwhen you meantof.for (const x in [10, 20])logs'0'and'1'instead of10and20. If your values come out as numeric strings, check the keyword. - Using
for...ofon a plain object. This throws "is not iterable". UseObject.keys,Object.valuesorObject.entries. - Reassigning a
constloop variable. Switch toletor use a new variable. - Expecting
awaitinside the head to work over promises.for (const p of promises)gives you the promise objects, not their results. Usefor await...of, covered later, orawaiteach value in the body. - Assuming holes are skipped. Only
forEach,mapand similar array methods skip them.for...ofdoes not.
Exercise
What does this code log, and why? const tags = ['a', 'b']; tags.note = 'hi'; for (const t of tags) console.log(t);
Show answer
It logs 'a' and then 'b'. for...of on an array visits only the indexed elements from 0 to length - 1. It ignores the extra note property, which for...in would have included.
Exercise
A function loadUsers() returns an array and logs "loading" each time it runs. How many times does "loading" appear when you run for (const u of loadUsers()) { console.log(u); } over an array of five users?
Show answer
Once. The iterable expression after of is evaluated a single time before the first iteration, no matter how many values it produces.
Exercise
Rewrite for (const n of nums) { n = Math.abs(n); console.log(n); } so it runs without throwing, keeping the variable name n.
Show answer
Declare the loop variable with let: for (let n of nums) { n = Math.abs(n); console.log(n); }. Each iteration still gets its own binding, and let allows reassignment. Alternatively, keep const and log Math.abs(n) directly.
Exercise
What does for (const v of [ , 'b']) console.log(v); print, and how would [ , 'b'].forEach(v => console.log(v)) differ?
Show answer
The for...of loop prints undefined and then 'b', because it visits every index including the hole. The forEach call prints only 'b', because forEach skips holes.