Q4: Implement a polyfill for Array.prototype.forEach().
Answer
The forEach() method executes a callback for every existing element in an array. It returns undefined and does not build a result array.
Array.prototype.myForEach = function (callback, thisArg) {
if (this == null) {
throw new TypeError("Array.prototype.myForEach called on null or undefined");
}
if (typeof callback !== "function") {
throw new TypeError("Callback must be a function");
}
const array = Object(this);
const length = array.length >>> 0;
for (let i = 0; i < length; i++) {
if (i in array) {
callback.call(thisArg, array[i], i, array);
}
}
};
const result = [10, 20, 30].myForEach((value, index) => {
console.log(index, value);
});
console.log(result); // undefined
Explanation
- The callback executes for each existing index.
- The original array is not automatically modified, although the callback can modify it.
forEach()cannot be stopped early withbreakor a callback return value.- The iteration length is captured before the loop, matching native behavior more closely than repeatedly reading the length.
Key Takeaways
- ForEach executes callbacks for side effects and returns undefined.
- A callback's return value does not control iteration.