On this page
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
forEachreturn?undefined. It exists only for side effects. - Should the original array be mutated? No.
mapandfilterreturn 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:
forEachignores the result.mapstores the result at the same index of a new array.filterkeeps 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 callsffor index 1.myForEachandmyFilterskip it too. - The callback pushes to the array while looping: elements added later are not visited, because
lenwas read before the loop. - The callback deletes an element that has not been visited yet: it is skipped, because
i in thisis checked on every iteration. - An empty array: the callback is never called.
myMapandmyFilterreturn[]. thisArgis ignored when the callback is an arrow function, as with the built-ins.
Follow-ups
- How do you stop
forEachearly? You cannot —returnonly ends the current callback, andbreakis a syntax error there. Use afor...ofloop, orsome/every, which stop on their own. - What is the difference between
forEachandmap?mapreturns a new array of the results.forEachreturnsundefined. - Write
mapandfilterusing onlyreduce. 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, 3done 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
asynccallback returns a promise as soon as it reaches its firstawait, andforEachdrops that promise and moves to the next element. awaitonly pauses the function it is written in. Here that is the callback, notrun, soruncarries on toconsole.log('done').- Nothing is holding the promises, so a
try...catcharound theforEachcannot catch an error thrown after anawait. 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 doneasync 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 doneasync 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, doneCommon mistakes
- Using
pushinmap, which collapses holes and shifts indices. - Returning the array from
forEach— the built-in returnsundefined, so it cannot be chained. - Forgetting the
indexandarrayarguments to the callback. - Ignoring
thisArg. - Writing the polyfill as an arrow function, which loses
this(the array the method was called on).
Related
- Concepts: call, apply and bind in the JavaScript track, for how
cb.call(thisArg, …)setsthis. sleepused in the async example: sleep and timeout.- Next: reduce and reduceRight.