Array.prototype.forEachLoading saved progress…

Array.prototype.forEach

Array.prototype.forEach runs a function once for every element of an array, in order, purely for its side effects — it always returns undefined. It's the loop you reach for when you want to do something with each item (log it, push it somewhere) rather than build a new array.

Implement arrayForEach(arr, callback, thisArg). Walk arr from index 0 upward and call callback for each element with three arguments: the element's value, its index, and the whole array. If thisArg is supplied, it becomes this inside the callback. The function returns nothing.

Signature

function arrayForEach(arr, callback, thisArg) {
  // calls callback(value, index, arr) for each element,
  // with `this` set to thisArg; returns undefined.
}

Examples

const out = [];
arrayForEach(['a', 'b', 'c'], (value, index) => out.push(index + ':' + value));
out; // ['0:a', '1:b', '2:c']
// Holes in a sparse array are skipped, not visited as undefined:
const seen = [];
arrayForEach([1, , 3], (value, index) => seen.push(index));
seen; // [0, 2]

Notes

  • Three arguments — the callback receives (value, index, array). Many callers use only the first one, but all three must be passed.
  • Return valueforEach always returns undefined. It is used for side effects, never for its result.
  • Sparse holes — an array literal like [1, , 3] has a hole at index 1. Skip holes entirely; don't call the callback with undefined for them.
  • thisArg — when provided, it sets this inside a regular (non-arrow) callback. When omitted, this is undefined in strict mode.
  • Don't build or return a new array — that's map. This is a read-only walk over the input.
Loading editor…