Skip to content
jshacks.dev
Fundamentals

for in vs for of vs forEach in JavaScript Loops Compared

for...in walks keys, for...of walks values of an iterable and forEach calls a function per item. See the traps with indexes, inheritance, break and await.

8 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, Node.js, Vite, npm and TypeScript logos.

Three loop forms handle "do something for each item", and they look similar enough that people use them interchangeably until one of them misbehaves. The for...in loop over an array gives strings and sometimes extra keys. The forEach that never stops when you return. The for...of over an object that throws. Each has a job, and the jobs do not overlap as much as the names suggest. This post compares them on the same data with output from Node.js 24, covers the cases where each one fails, and ends on a rule for choosing. The array method has its own post in the forEach() post, and the protocol for...of relies on is in the post on iterators and iterables.

The same data, three loops

Loop over one array with each form and compare what the variable holds.

JavaScript
const letters = ["a", "b", "c"];

for (const key in letters) {
  console.log("in:", key, typeof key);
}

for (const value of letters) {
  console.log("of:", value);
}

letters.forEach((value, index) => {
  console.log("forEach:", index, value);
});
Text
in: 0 string
in: 1 string
in: 2 string
of: a
of: b
of: c
forEach: 0 a
forEach: 1 b
forEach: 2 c

for...in gave the indexes, and as strings, not numbers: "0", "1", "2". for...of gave the values. forEach gave both, as arguments to a callback. The first form is for keys, the second for values, and the third is a method on arrays with a different control flow, covered below.

Why for...in is wrong for arrays

for...in enumerates every enumerable property, including ones inherited through the prototype chain and ones added to the array object itself. Indexes are only one kind of property.

JavaScript
const scores = [10, 20];
scores.label = "extra";

const base = { inheritedKey: true };
const child = Object.create(base);
child.own = 1;

const forArray = [];
for (const key in scores) forArray.push(key);

const forObject = [];
for (const key in child) forObject.push(key);

console.log(forArray);
console.log(forObject);
console.log(Object.keys(child));

const sum = [];
for (const index in [5, 6]) sum.push(index + 1);
console.log(sum);
Text
[ '0', '1', 'label' ]
[ 'own', 'inheritedKey' ]
[ 'own' ]
[ '01', '11' ]

The array loop returned the extra label property along with the indexes. The object loop returned the inherited key as well as the own one, while Object.keys() returned only the own key. The last line is the classic bug: the index is a string, so adding one concatenates and gives "01" and "11". Libraries that extend Array.prototype with enumerable methods also appear in for...in, which was a real hazard in older code. A guard with Object.hasOwn(obj, key) helps for objects, and for arrays the answer is to use for...of.

for...of and what it accepts

for...of works on any iterable: arrays, strings, sets, maps, typed arrays, generators and the results of Object.entries(). It does not work on plain objects.

JavaScript
const iterables = {
  string: "hi",
  set: new Set([1, 2]),
  map: new Map([["k", "v"]]),
  entries: Object.entries({ x: 1, y: 2 }),
};

for (const [label, source] of Object.entries(iterables)) {
  const items = [];
  for (const item of source) items.push(item);
  console.log(label, items);
}

try {
  for (const item of { a: 1 }) console.log(item);
} catch (error) {
  console.log(error.name);
}

for (const [key, value] of Object.entries({ name: "Ada", role: "admin" })) {
  console.log(key, "=", value);
}
Text
string [ 'h', 'i' ]
set [ 1, 2 ]
map [ [ 'k', 'v' ] ]
entries [ [ 'x', 1 ], [ 'y', 2 ] ]
TypeError
name = Ada
role = admin

Each iterable yielded its natural items: characters, set members, [key, value] pairs for a map. The object failed with a TypeError. The recommended way to loop over an object is Object.entries(), which returns an array of pairs that for...of can destructure, and it includes only own enumerable properties, which makes the inherited-key problem disappear.

Control flow: break, continue and await

Only the statement forms can use break, continue, return and await. A forEach callback is a function, so its return leaves the callback only.

JavaScript
const numbers = [1, 2, 3, 4, 5];

const viaForOf = [];
for (const n of numbers) {
  if (n === 2) continue;
  if (n === 4) break;
  viaForOf.push(n);
}

const viaForEach = [];
numbers.forEach((n) => {
  if (n === 2) return;
  if (n === 4) return;
  viaForEach.push(n);
});

console.log(viaForOf);
console.log(viaForEach);

function firstEven(list) {
  for (const n of list) {
    if (n % 2 === 0) return n;
  }
  return undefined;
}

console.log(firstEven([1, 3, 6, 7]));
Text
[ 1, 3 ]
[ 1, 3, 5 ]
6

for...of skipped 2 and stopped at 4. The forEach version could not stop: its return acted like continue, so 5 was still collected. And a return inside a for...of inside a function returns from the function, which is how firstEven finds its answer without visiting the rest. Use a statement loop whenever you need early exit.

Async work

for...of pauses at each await, so iterations run one after another. forEach starts every callback and does not wait.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

const log = [];

for (const id of [1, 2]) {
  await sleep(5);
  log.push("for-of " + id);
}
log.push("after for-of");

[3, 4].forEach(async (id) => {
  await sleep(5);
  log.push("forEach " + id);
});
log.push("after forEach");

await sleep(30);

console.log(log);
Text
[
  'for-of 1',
  'for-of 2',
  'after for-of',
  'after forEach',
  'forEach 3',
  'forEach 4'
]

The for...of loop finished before the line after it ran. The forEach line after the loop ran before any callback finished, and the callbacks completed later. For concurrent work, map to promises and await Promise.all(...), as described in the forEach() post. The loop form decides whether your code waits.

The classic for loop

The three-part for loop remains useful when you need the index as a number, a reverse walk, a step other than one or the last bit of speed in an inner loop.

JavaScript
const items = ["a", "b", "c", "d"];

for (let i = items.length - 1; i >= 0; i--) {
  console.log(i, items[i]);
}

for (let i = 0; i < items.length; i += 2) {
  console.log("even position", items[i]);
}
Text
3 d
2 c
1 b
0 a
even position a
even position c

A reverse loop is the one place the classic form is clearly the best, since for...of has no reverse. For ordinary forward iteration, the index is rarely needed, and for (const [i, item] of items.entries()) provides it without a counter, as covered in the entries() post.

Changing the collection while looping

Each form reacts differently when the collection changes during the loop, and the safest habit is not to change it. The array forms see appended items differently, and removing items shifts the positions the loop has not reached yet.

JavaScript
const queue = ["a", "b", "c"];
const seenOf = [];
for (const item of queue) {
  seenOf.push(item);
  if (item === "a") queue.push("d");
}

const second = ["a", "b", "c"];
const seenEach = [];
second.forEach((item) => {
  seenEach.push(item);
  if (item === "a") second.push("d");
});

const removal = ["x", "y", "z", "w"];
const seenRemoval = [];
for (const item of removal) {
  seenRemoval.push(item);
  if (item === "x") removal.splice(0, 1);
}

console.log(seenOf);
console.log(seenEach);
console.log(seenRemoval);
Text
[ 'a', 'b', 'c', 'd' ]
[ 'a', 'b', 'c' ]
[ 'x', 'z', 'w' ]

The for...of loop reached the appended "d", because the array iterator checks the length on every step. The forEach loop fixed its range at the start and never saw it. Removing the first item while on it shifted everything left, so the loop skipped "y". The reliable patterns are to loop over a copy, for (const item of [...queue]), or to collect changes and apply them after the loop ends. For a queue that must grow during processing, a while (queue.length) loop with shift() is clearer than relying on iterator behavior.

What to do in a code review

When a pull request adds a loop, three comments cover most of what goes wrong. If the loop is a for...in over an array, ask for for...of, because the string index and the inherited keys are bugs waiting for data. If it is a forEach with an async callback, ask what waits for the work, and offer for...of or Promise.all. And if it mutates the collection it iterates, ask for a copy first. Each comment points at a real failure mode, so it reads as help and not as taste.

Linting the choice

Three ESLint rules turn the preferences above into checks. guard-for-in flags a for...in without an Object.hasOwn guard. no-restricted-syntax can ban ForInStatement outright in application code. And @typescript-eslint/no-misused-promises flags an async callback passed to forEach, which catches the unawaited work described above. They cost almost nothing to enable and remove the common mistakes from review.

A rule for choosing

You wantUse
The values of an array, set, map or stringfor...of
The keys and values of an objectfor...of over Object.entries()
The index and the valuefor...of over .entries()
To stop early, skip items, or await in orderfor...of
A simple synchronous effect on every itemforEach() is fine
The own enumerable keys of an object, no valuesObject.keys()
A reverse walk or a strideA classic for
Inherited enumerable keys, deliberatelyfor...in

If you are choosing between for...of and forEach() and have no reason to prefer the callback, choose for...of. We avoid for...in in application code and reach for it only when walking a prototype chain on purpose.

Where this advice stops

forEach() is entirely reasonable for short synchronous work, such as registering listeners or logging, and a style guide that bans it outright costs readability. Functional chains of map, filter and reduce are a different tool for producing values and do not replace loops that perform effects. And for very hot loops over large arrays, the classic for is the fastest form in most engines, though we would not sacrifice clarity without a profile that points at it.

The statements are defined in the specification under iteration statements, and MDN's pages on for...in and for...of compare them directly.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.