Watch 10 video solutions for Array Prototype ForEach, a easy level problem. This walkthrough by Nick White has 112,644 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
Write your version of method forEach that enhances all arrays such that you can call the array.forEach(callback, context) method on any array and it will execute callback on each element of the array. Method forEach should not return anything.
callback accepts the following arguments:
currentValue - represents the current element being processed in the array. It is the value of the element in the current iteration.index - represents the index of the current element being processed in the array.array - represents the array itself, allowing access to the entire array within the callback function.The context is the object that should be passed as the function context parameter to the callback function, ensuring that the this keyword within the callback function refers to this context object.
Try to implement it without using the built-in array methods.
Example 1:
Input:
arr = [1,2,3],
callback = (val, i, arr) => arr[i] = val * 2,
context = {"context":true}
Output: [2,4,6]
Explanation:
arr.forEach(callback, context)
console.log(arr) // [2,4,6]
The callback is executed on each element of the array.
Example 2:
Input:
arr = [true, true, false, false],
callback = (val, i, arr) => arr[i] = this,
context = {"context": false}
Output: [{"context":false},{"context":false},{"context":false},{"context":false}]
Explanation:
arr.forEach(callback, context)
console.log(arr) // [{"context":false},{"context":false},{"context":false},{"context":false}]
The callback is executed on each element of the array with the right context.
Example 3:
Input:
arr = [true, true, false, false],
callback = (val, i, arr) => arr[i] = !val,
context = {"context": 5}
Output: [false,false,true,true]
Constraints:
arr is a valid JSON arraycontext is a valid JSON objectfn is a function0 <= arr.length <= 105Problem Overview: Implement Array.prototype.forEach. The method receives a callback function and executes it once for every element in the array. The callback typically receives (element, index, array) and the method returns undefined.
Approach 1: Simple Iterative Implementation (O(n) time, O(1) space)
The most direct solution iterates through the array using a standard for loop. For each index i, call the provided callback with the current value, index, and the array itself: fn(this[i], i, this). The key idea is that the method runs exactly once per element, so a single pass over the array is sufficient. No extra data structures are required, which keeps space usage constant. This mirrors how many built-in array iteration utilities work internally.
Inside the prototype method, this refers to the array instance that called forEach. A loop from 0 to this.length - 1 ensures every element is processed in order. After executing the callback for each element, the function implicitly returns undefined, matching the behavior of the native implementation. Time complexity is O(n) because each element is visited once, and space complexity remains O(1).
Approach 2: Spec‑Compliant Iteration with Sparse Array Handling (O(n) time, O(1) space)
A more accurate implementation follows JavaScript's behavior for sparse arrays. Some arrays contain "holes" where an index exists in the range but no value is stored. To match native behavior, check if (i in this) before executing the callback. This prevents invoking the function for missing elements. The callback is then invoked with fn.call(thisArg, this[i], i, this) if a context parameter is provided.
This approach still performs a single linear scan across the array. The difference lies in correctly handling edge cases defined in the JavaScript specification. It also demonstrates how prototype methods work in core language fundamentals, particularly how functions interact with this and array indices.
Recommended for interviews: Interviewers usually expect the simple linear iteration approach. Showing a clean for loop that calls the callback with the correct arguments demonstrates understanding of prototypes and array iteration. Mentioning sparse array handling and thisArg support shows deeper knowledge of JavaScript internals.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Simple Iterative Implementation | O(n) | O(1) | Best for interviews and most implementations where every array element should trigger the callback |
| Spec‑Compliant Iteration (Skip Sparse Elements) | O(n) | O(1) | When matching native JavaScript behavior, including sparse arrays and optional callback context |