On this page
Tracks

Polyfill: forEach, map and filterhigh-yield

Last reviewed 6 Oct 2026

Problem

Implement myForEach, myMap and myFilter on Array.prototype, matching the built-ins:

[1, 2, 3].myForEach((x) => console.log(x)); // logs 1, 2, 3 — returns undefined
[1, 2, 3].myMap((x) => x * 2); // [2, 4, 6]
[1, 2, 3, 4].myFilter((x) => x % 2 === 0); // [2, 4]

Clarifying questions

  • Does the callback receive (element, index, array)? Yes, all three.
  • Should the methods accept a thisArg? Yes, the built-ins do.
  • Should holes in sparse arrays ([1, , 3]) be skipped? Yes — the built-ins skip them.
  • What does forEach return? undefined. It exists only for side effects.
  • Should the original array be mutated? No. map and filter return a new array.

Approach

All three are the same loop with a different thing done to the callback’s result. Loop over the indices, skip holes with i in this, and call the callback with the element, its index and the array:

  • forEach ignores the result.
  • map stores the result at the same index of a new array.
  • filter keeps the element when the result is truthy.

Step-by-step build

Step 1 — myForEach

Array.prototype.myForEach = function (cb, thisArg) {
for (let i = 0; i < this.length; i++) {
if (i in this) cb.call(thisArg, this[i], i, this);
}
};

There is no return, so the method returns undefined.

Step 2 — myMap

Array.prototype.myMap = function (cb, thisArg) {
const out = new Array(this.length);
for (let i = 0; i < this.length; i++) {
if (i in this) out[i] = cb.call(thisArg, this[i], i, this);
}
return out;
};

Assigning to out[i] instead of pushing keeps holes as holes and keeps every result at its original index.

Step 3 — myFilter

Array.prototype.myFilter = function (cb, thisArg) {
const out = [];
for (let i = 0; i < this.length; i++) {
if (i in this && cb.call(thisArg, this[i], i, this)) out.push(this[i]);
}
return out;
};

Step 4 — validate the callback and read the length once

if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
const len = this.length;

The built-ins read length once, before the loop starts. Caching it gives the same behaviour when the callback adds elements.

Final code

Array.prototype.myForEach = function (cb, thisArg) {
if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
const len = this.length;
for (let i = 0; i < len; i++) {
if (i in this) cb.call(thisArg, this[i], i, this);
}
};
Array.prototype.myMap = function (cb, thisArg) {
if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
const len = this.length;
const out = new Array(len);
for (let i = 0; i < len; i++) {
if (i in this) out[i] = cb.call(thisArg, this[i], i, this);
}
return out;
};
Array.prototype.myFilter = function (cb, thisArg) {
if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
const len = this.length;
const out = [];
for (let i = 0; i < len; i++) {
if (i in this && cb.call(thisArg, this[i], i, this)) out.push(this[i]);
}
return out;
};

Edge cases

  • Sparse arrays: [1, , 3].myMap(f) keeps the hole and never calls f for index 1. myForEach and myFilter skip it too.
  • The callback pushes to the array while looping: elements added later are not visited, because len was read before the loop.
  • The callback deletes an element that has not been visited yet: it is skipped, because i in this is checked on every iteration.
  • An empty array: the callback is never called. myMap and myFilter return [].
  • thisArg is ignored when the callback is an arrow function, as with the built-ins.

Follow-ups

  • How do you stop forEach early? You cannot — return only ends the current callback, and break is a syntax error there. Use a for...of loop, or some / every, which stop on their own.
  • What is the difference between forEach and map? map returns a new array of the results. forEach returns undefined.
  • Write map and filter using only reduce. Worked through on the reduce and reduceRight page.

Why await inside forEach does not wait

This is asked often enough to prepare on its own. What does this log?

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function run() {
[1, 2, 3].forEach(async (n) => {
await sleep(100);
console.log(n);
});
console.log('done');
}
run(); // done, 1, 2, 3

done is logged first, and then 1, 2, 3 arrive together after 100 ms — not one every 100 ms.

The polyfill shows why. The whole loop body is this line:

if (i in this) cb.call(thisArg, this[i], i, this);
  • The return value of the callback is thrown away. An async callback returns a promise as soon as it reaches its first await, and forEach drops that promise and moves to the next element.
  • await only pauses the function it is written in. Here that is the callback, not run, so run carries on to console.log('done').
  • Nothing is holding the promises, so a try...catch around the forEach cannot catch an error thrown after an await. It becomes an unhandled rejection.

The fix depends on whether the work should run one item at a time or all together.

// One after another: 1, 2, 3 at 100 ms intervals, then done
async function inSequence() {
for (const n of [1, 2, 3]) {
await sleep(100);
console.log(n);
}
console.log('done');
}
// All at once: 1, 2, 3 together after 100 ms, then done
async function inParallel() {
await Promise.all([1, 2, 3].map(async (n) => {
await sleep(100);
console.log(n);
}));
console.log('done');
}

map works where forEach does not because it keeps what the callback returns, so Promise.all has the promises to wait for.

A common next question is to write a forEach that does wait. Make the method itself async and await each call:

Array.prototype.myForEachAsync = async function (cb, thisArg) {
const len = this.length;
for (let i = 0; i < len; i++) {
if (i in this) await cb.call(thisArg, this[i], i, this);
}
};
await [1, 2, 3].myForEachAsync(async (n) => {
await sleep(100);
console.log(n);
});
console.log('done'); // 1, 2, 3, done

Common mistakes

  • Using push in map, which collapses holes and shifts indices.
  • Returning the array from forEach — the built-in returns undefined, so it cannot be chained.
  • Forgetting the index and array arguments to the callback.
  • Ignoring thisArg.
  • Writing the polyfill as an arrow function, which loses this (the array the method was called on).