Other Polyfills to Practice for Interviews
Beyond bind: polyfills for map, filter, reduce, and Promise.all.
Other Polyfills to Practice for Interviews
map Polyfill
Array.prototype.myMap = function (callback, thisArg) { const result = []; for (let i = 0; i < this.length; i++) { result.push(callback.call(thisArg, this[i], i, this)); } return result; };
filter Polyfill
Array.prototype.myFilter = function (callback, thisArg) { const result = []; for (let i = 0; i < this.length; i++) { if (callback.call(thisArg, this[i], i, this)) result.push(this[i]); } return result; };
reduce Polyfill
Array.prototype.myReduce = function (callback, initialValue) { let acc = initialValue; let start = 0; if (initialValue === undefined) { if (this.length === 0) throw new TypeError("Reduce of empty array with no initial value"); acc = this[0]; start = 1; } for (let i = start; i < this.length; i++) { acc = callback(acc, this[i], i, this); } return acc; };
Promise.all Polyfill
function myPromiseAll(promises) { return new Promise((resolve, reject) => { const results = []; let completed = 0; promises.forEach((promise, index) => { Promise.resolve(promise).then((value) => { results[index] = value; if (++completed === promises.length) resolve(results); }).catch(reject); }); }); }
The Takeaway
Practice these polyfills: map (loop, call callback, push result), filter (loop, call callback, push if truthy), reduce (handle initial value, loop, update accumulator), and Promise.all (resolve all, count completed, reject on any failure). These are common interview questions.
Loop through the array, call the callback with (element, index, array), push the result to a new array, return it. Use let in the loop and do not mutate the original.
Handle the initial value: if provided, start with it at index 0; if not, use the first element at index 1. Throw TypeError for empty arrays without initial value. Loop and update the accumulator.
Return a new Promise. Track completed count. For each promise, resolve and store the result at its index. When all complete, resolve with the results array. If any rejects, reject immediately.
Three arguments: the current element, the current index, and the array itself. Use callback.call(thisArg, this[i], i, this) to support the optional thisArg parameter.
Because without an initial value, reduce uses the first element as the accumulator. An empty array has no first element. The spec requires: TypeError: Reduce of empty array with no initial value.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

