Implement arrayForEach (no prototype mutation)

intermediate
By FrontendAtlas Editorial · Updated Oct 15, 2026
You should also ensure the callback is invoked with the correct thisArg and that the method returns undefined like the native API. Edge cases include sparse arrays and thisArg binding; test callback order and performance with large arrays.

Arguments

  • arr: Array<any> — Source array to iterate. Sparse slots must be skipped.
  • callbackFn: (value:any, index:number, array:any[]) => void — Function to invoke for each present element.
  • thisArg: any (optional) — Value of this inside callbackFn.

Returns

void — No return value (returns undefined).

Solution idea

A correct polyfill mirrors the ECMAScript behavior: skip holes, use length snapshotting, and validate the callback before iterating.

Examples
// Sum values
let sum = 0; arrayForEach([1,2,3], v => { sum += v; }); // sum = 6

// Respect thisArg
const ctx = { seen: [] }; arrayForEach(['a','b'], function (v) { this.seen.push(v); }, ctx); // ctx.seen = ['a','b']

// Skip holes
const a = [1, , 3]; arrayForEach(a, (v, i) => { /* called for i=0 and i=2 only */ });

Public interview reports

These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.

Reported in a public ServiceNow interview account. ServiceNow frontend interview questions