FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Implement arrayForEach (no prototype mutation)

Implement arrayForEach (no prototype mutation)

intermediate
By FrontendAtlas Editorial · Updated Jan 30, 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).
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 */ });

Solution

Overview

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

1

Single approach: length snapshot + own-property check (recommended)

If length changes during iteration, native forEach uses the original length; you can mention this even if the simplified solution doesn’t implement it fully. Include a note about converting array-like values with Object(this).

export default function arrayForEach(arr, callbackFn, thisArg) {
  if (!Array.isArray(arr)) throw new TypeError('arr must be an array');
  if (typeof callbackFn !== 'function') throw new TypeError('callbackFn must be a function');

  const len = arr.length; // snapshot once
  const hasOwn = Object.prototype.hasOwnProperty;

  for (let i = 0; i < len; i++) {
    if (hasOwn.call(arr, i)) {
      callbackFn.call(thisArg, arr[i], i, arr);
    }
  }

  return undefined;
}
export default function arrayForEach<T>(
  arr: (T | undefined)[],
  callbackFn: (value: T, index: number, array: (T | undefined)[]) => void,
  thisArg?: any,
): void {
  if (!Array.isArray(arr)) throw new TypeError('arr must be an array');
  if (typeof callbackFn !== 'function') throw new TypeError('callbackFn must be a function');

  const len = arr.length; // snapshot once
  const hasOwn = Object.prototype.hasOwnProperty;

  for (let i = 0; i < len; i++) {
    if (hasOwn.call(arr, i)) {
      callbackFn.call(thisArg, arr[i] as T, i, arr);
    }
  }
}

Notes & Pitfalls

Pitfalls
  • If you use `for (let i = 0; i < arr.length; i++)`, you may accidentally iterate elements appended during iteration.
  • If you don’t check for existence, you’ll call the callback on holes (native forEach skips them).
  • `thisArg` won’t affect arrow functions (they don’t bind `this`).
Edge cases
  • Sparse arrays like `[1, , 3]`: callback runs for indices 0 and 2 only.
  • Delete-before-visit: if index 1 is deleted while processing index 0, index 1 must be skipped.
  • Push-during-iteration: elements appended after the call starts must not be visited.
Techniques
  • Snapshot length once.
  • Use `hasOwnProperty.call(arr, i)` to skip holes and to respect delete-before-visit.
  • Use `.call(thisArg, value, index, array)` to bind context.

Common mistakes on this challenge

  • arrayForEach loop semantics are off

    forEach-like behavior requires stable order, optional thisArg binding, and sparse-array awareness.

    • Validate `arr` is an array and `callbackFn` is a function.
    • Snapshot `arr.length` once before iteration.
    • Visit only existing indices and call `callbackFn.call(thisArg, value, index, arr)`.

Resources

  • MDN – Array.prototype.forEach()
  • ECMAScript Spec – Array.prototype.forEach

Similar questions

Implement Array.prototype.filterintermediateImplement Array.prototype.mapintermediateImplement Array.prototype.reduceintermediate

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
← Prev←59 / 88Next →→