Hiprup

What is the difference between for, for...in, for...of, and forEach?

Four ways to loop, each suited to different needs.

  • for — classic index-based; full control with break and continue.

  • for...in — iterates object keys (and inherited ones); for objects, not arrays.

  • for...of — iterates values of any iterable; the modern choice for arrays.

  • forEach — an array method running a callback per item; can't break out.

Quick guide: for...of for array values, for...in for object keys, forEach for simple side effects, classic for when you need index control or early exit.

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

// for — full control
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 'b') break; // Can break!
  console.log(i, arr[i]);
}

// for...of — values (iterables)
for (const val of arr) {
  console.log(val); // 'a', 'b', 'c'
}

// for...in — keys (objects)
const obj = { x: 1, y: 2, z: 3 };
for (const key in obj) {
  console.log(key, obj[key]); // 'x' 1, 'y' 2, 'z' 3
}

// forEach — no break
arr.forEach((val, i) => {
  console.log(i, val); // 0 'a', 1 'b', 2 'c'
  // return; // Skips rest of THIS callback, not the loop
});

Classic for: index access, break/continue. for...of: values directly from iterables. for...in: string keys from objects (not for arrays — includes prototype). forEach: clean but no break/continue (return only exits the current callback, not the loop).

Know when to use each: for (full control), for...of (array values), for...in (object keys), forEach (simple, no break). for...in on arrays is dangerous (includes prototype). forEach cannot break — this is the most asked detail.

What is the difference between for, for...in, for...of, and forEach? | Hiprup