Compare for...in, for...of and Array.prototype.forEach. What does each one iterate over, and when would you pick each in real code?
Show the explanation
Model answer.
- `for...in` iterates over enumerable property keys (strings) of an object, including inherited ones. Good for plain objects; risky for arrays, because keys are strings and order or extra properties can surprise you.
- `for...of` iterates over the values of any iterable: arrays, strings,
Map,Set,NodeList, generators. - `forEach` is an array method that calls a function for each element.
const marks = [70, 85];
for (const i in marks) console.log(typeof i); // 'string', 'string'
for (const m of marks) console.log(m); // 70, 85
marks.forEach((m, i) => console.log(i, m));Practical choice:
- Arrays:
for...of, which supportsbreak,continueandawaitinside the loop.forEachcannot be stopped early, andawaitinside its callback does not pause the loop. - Plain objects:
Object.entries(obj)withfor...of, rather thanfor...in.
Original UniCircle question. Last reviewed 22 Oct 2026.
