Sub topic 6
for...of: Walking the Values of an Iterable
This chapter assumes you know let and const, can work with arrays and objects, and have read the earlier chapters on for...in. Here the focus moves from property keys to values.
The basic shape
A for...of loop takes each value from an iterable and runs the loop body once for that value. An iterable is any object that can hand out its values one at a time. Arrays, strings, Maps and Sets are all iterables.
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// red
// green
// blueThe loop head has three parts:
- A declaration, here
const color, which receives each value in turn. - The keyword
of. - An expression that evaluates to an iterable, here
colors.
You never touch an index, a length or bracket access. The loop gives you the value directly.
Why `const` works here
It can look odd to declare the loop variable with const when it changes on every pass. It works because each iteration gets a fresh binding. You are not reassigning one variable. A new color is created for each value. Use const unless you plan to reassign the variable inside the body, and then use let. A later chapter explains why this per-iteration binding matters for closures.
const temps = [18, 21, 25];
for (let t of temps) {
t = t * 1.8 + 32; // reassigning needs let
console.log(t.toFixed(1));
}
// 64.4
// 69.8
// 77.0
console.log(temps); // [18, 21, 25]: the array is unchangedReassigning the loop variable does not change the collection. The variable holds a copy of the value. Object values are the exception in practice: if a value is an object, you can still mutate that object through the variable.
Keys versus values, side by side
const pets = ['cat', 'dog'];
for (const k in pets) console.log(k); // '0', '1'
for (const v of pets) console.log(v); // 'cat', 'dog'for...in asks "what are the property names?" for...of asks "what values does this collection produce?"
The common error: non-iterables
Plain objects are not iterable, so for...of cannot loop over them directly:
const config = { debug: true };
try {
for (const v of config) {}
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "config is not iterable"
}The check happens when the loop starts, before the body runs even once. The same TypeError appears for null, undefined and numbers. If you need to walk an object, a later chapter shows how to use Object.entries with for...of.
Exercise
What does this code print, and why? const nums = [1, 2]; for (let n of nums) { n *= 10; } console.log(nums);
Show answer
It prints [1, 2]. Each iteration binds n to a copy of the number, so reassigning n changes only the loop variable and leaves the array as it was.
Exercise
You write for (const item of getItems()) and get "TypeError: getItems(...) is not iterable". Name two likely causes.
Show answer
getItems returned a plain object instead of an array or other iterable, or it returned undefined, for example because a return statement is missing.