← JavaScript

Basic · 6 of 12 · 13 min read

for, for...in and for...of

Three loops that look alike and iterate different things, plus which ones you can break out of and why that matters.

  • Control flow

JavaScript has three for loops and they are not variations on each other — they iterate different things. Picking the wrong one is one of the most common sources of quietly wrong code.

The three, side by side

const letters = ['a', 'b', 'c'];

for (let i = 0; i < letters.length; i++) {
  console.log(i, letters[i]);          // 0 a / 1 b / 2 c
}

for (const key in letters) {
  console.log(key, typeof key);        // "0" string / "1" string / "2" string
}

for (const value of letters) {
  console.log(value);                  // a / b / c
}
Loop Iterates Gives you Works on
for (;;) an index you manage a number anything with a length
for...in enumerable keys a string objects (and arrays, badly)
for...of values the element arrays, strings, Set, Map, generators

Classic for

let i = 0 init — once i < n true run the body body i++ update next iteration false after the loop
The three clauses of the header live at three different places in the cycle: the initialiser outside it, the condition at the top, the update at the bottom. That is why a continue still increments i — it jumps to the update, which belongs to the loop, not to the body.

The three clauses are all optional, and the counter is a normal variable — which is why let matters here more than anywhere else:

// Count down
for (let i = 3; i > 0; i--) console.log(i); // 3 / 2 / 1

// Two counters
for (let i = 0, j = 10; i < j; i++, j--) {
  if (i === 2) console.log(i, j);           // 2 8
}

// No clauses at all — the loop body decides
let n = 0;
for (;;) {
  n += 1;
  if (n === 3) break;
}
console.log(n); // 3

let gives each iteration its own binding; var gives the whole function one. That is the entire explanation of the most famous closure puzzle in JavaScript:

const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
console.log(withVar.map((f) => f())); // [3, 3, 3] — one shared `i`, left at 3

const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withLet.map((f) => f())); // [0, 1, 2] — a fresh `j` each time

for...in iterates keys, and more of them than you expect

Two surprises, both of which make it the wrong tool for arrays.

The keys are strings, because object keys always are:

const letters = ['a', 'b'];
for (const i in letters) {
  console.log(i + 1);   // "01" then "11"  ← string concatenation, not arithmetic
  console.log(+i + 1);  // 1 then 2        ← coerced back to a number
}

It walks the prototype chain, so anything added to Array.prototype or an object’s prototype shows up:

const parent = { inherited: 1 };
const child = Object.create(parent);
child.own = 2;

for (const key in child) console.log(key);   // "own" then "inherited"
console.log(Object.keys(child));             // ["own"] — own enumerable only

For objects, the modern forms are clearer and do not inherit:

const prices = { a: 1, b: 2 };

console.log(Object.keys(prices));    // ["a", "b"]
console.log(Object.values(prices));  // [1, 2]
console.log(Object.entries(prices)); // [["a", 1], ["b", 2]]

for (const [key, value] of Object.entries(prices)) {
  console.log(key, value);           // a 1 / b 2
}

for...of works on anything iterable

Not just arrays — anything that implements the iteration protocol:

for (const c of 'hi') console.log(c);                 // h / i
for (const v of new Set([1, 1, 2])) console.log(v);   // 1 / 2
for (const [k, v] of new Map([['a', 1]])) console.log(k, v); // a 1

function* count() { yield 1; yield 2; }
for (const n of count()) console.log(n);              // 1 / 2

A plain object is not iterable, which is the one thing that trips people up:

// for (const v of { a: 1 }) {}   // TypeError: {} is not iterable
for (const v of Object.values({ a: 1 })) console.log(v); // 1

When you need the index as well, entries() gives you both:

for (const [i, letter] of ['a', 'b'].entries()) {
  console.log(i, letter); // 0 a / 1 b  ← i is a real number here
}

Stopping early

break leaves the loop, continue skips one iteration. Both work in all three for loops — and in none of the callback methods.

for (const n of [1, 2, 3, 4]) {
  if (n === 2) continue; // skip this one
  if (n === 4) break;    // leave entirely
  console.log(n);        // 1 / 3
}

This is the real reason to reach for for...of over forEach:

const nums = [1, 2, 3, 4];

// `forEach` cannot be stopped. `return` only ends the current callback.
nums.forEach((n) => {
  if (n === 2) return;  // skips, does not break
  console.log(n);       // 1 / 3 / 4  ← still visited 3 and 4
});

// The array methods that do stop have their own names:
console.log(nums.find((n) => n > 2));      // 3    — stops at the match
console.log(nums.some((n) => n > 2));      // true — stops at the first pass
console.log(nums.every((n) => n > 2));     // false — stops at the first failure

To break out of nested loops, label the outer one:

outer: for (const a of [1, 2]) {
  for (const b of [1, 2]) {
    if (b === 2) continue outer;
    console.log(a, b); // 1 1 / 2 1
  }
}

for await...of for asynchronous sources

The same loop, awaiting each value — for a paginated API or a stream:

async function* pages() {
  yield await Promise.resolve([1, 2]);
  yield await Promise.resolve([3]);
}

for await (const page of pages()) {
  console.log(page); // [1, 2] then [3]
}

Common mistakes

Using for...in on an array

Mistake. for (const i in items) total += items[i].price. Why it fails. The indexes arrive as strings, the order is not guaranteed by the loop itself, and anything on Array.prototype joins in. What to do instead. for (const item of items) for values, or items.entries() when you need the index too.

Expecting return to break a forEach

Mistake. items.forEach((i) => { if (found) return; … }) as an early exit. Why it fails. return ends that one callback invocation; the loop continues to the end of the array. What to do instead. for...of with break, or the method that already stops — find, some, every, findIndex.

Mutating the array you are iterating

Mistake. for (let i = 0; i < items.length; i++) if (bad(items[i])) items.splice(i, 1). Why it fails. Removing an element shifts the rest down, so the loop skips the next one. What to do instead. items = items.filter((i) => !bad(i)), or iterate backwards if you must mutate in place.

Check yourself

2 questions from the bank on what you just read. Answering here does not affect your quiz history.

When applied to an array, what does for...in iterate over?

You want to stop looping as soon as you find a match. Which of these can you break out of?

Practise Control flow →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.