CodeOath
← All posts
JavaScript65 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Contents — Part 5 of 16: Iterating Arrays
Part 5 of 16 · ~1 min

Iterating Arrays

[1, 2, 3].forEach((value, index, arr) => {
  console.log(value, index);
});

.forEach() runs a callback for each element but always returns undefined — a common mistake is trying to .map()-style transform data with .forEach() and use its return value, which doesn't exist. .forEach() also cannot be stopped early with break — a for...of loop or .some() (returning true to stop) are the alternatives when early exit is needed:

// This does NOT stop at 3, and its result is useless anyway:
const result = [1, 2, 3, 4].forEach(x => { if (x === 3) return; }); // result is undefined

// for...of CAN be stopped early:
for (const x of [1, 2, 3, 4]) {
  if (x === 3) break;
  console.log(x);
}

for...of iterates values directly and works on any iterable (arrays, strings, Map, Set); for...in iterates an object's enumerable keys (including inherited ones, which is why it's rarely the right tool for arrays — it can pick up unexpected properties and iterates in an unspecified order for non-integer keys).