Array Prototype ForEach - Problem
Implement your own version of the Array.prototype.forEach method that extends all arrays with a custom forEach functionality. Your implementation should allow calling array.forEach(callback, context) on any array to execute a callback function on each element.
The callback function receives three parameters:
currentValue- The current element being processedindex- The index of the current elementarray- Reference to the original array
The optional context parameter sets the this value inside the callback function. Your forEach method should not return anything (returns undefined).
Challenge: Implement this without using any built-in array methods!
Example:
[1, 2, 3].forEach((value, index, arr) => {
console.log(`Element ${value} at index ${index}`);
}); Input & Output
example_1.js โ Basic Usage
$
Input:
Array: [1, 2, 3]
Callback: (value, index, array) => console.log(`${value} at ${index}`)
โบ
Output:
1 at 0
2 at 1
3 at 2
return value: undefined
๐ก Note:
The forEach method calls the callback for each element, passing the current value, its index, and the original array. It returns undefined.
example_2.js โ With Context
$
Input:
Array: ['a', 'b', 'c']
Callback: function(value, index) { this.result.push(value.toUpperCase()); }
Context: { result: [] }
โบ
Output:
Context object after execution: { result: ['A', 'B', 'C'] }
return value: undefined
๐ก Note:
When a context object is provided, the callback's 'this' keyword refers to that context, allowing us to modify the context object.
example_3.js โ Empty Array
$
Input:
Array: []
Callback: (value, index, array) => console.log('Processing:', value)
โบ
Output:
return value: undefined
๐ก Note:
For empty arrays, the callback is never called, but forEach still returns undefined as expected.
Constraints
-
The method must be added to
Array.prototype - Must handle sparse arrays correctly (skip undefined indices)
- Must support optional context parameter for 'this' binding
-
Must return
undefined - Cannot use built-in array methods like map, filter, etc.
- Callback must receive exactly 3 parameters: (currentValue, index, array)
- Must throw appropriate errors for invalid callbacks
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Set up the conveyor belt (array) and assign the worker (callback function)
2
Process Each Item
For each item on the belt, call the worker with the item, its position, and reference to the whole belt
3
Context Binding
If specified, ensure the worker operates in the correct workspace (this context)
4
Complete
After all items are processed, the operation completes with no return value
Key Takeaway
๐ฏ Key Insight: forEach is fundamentally about controlled iteration - it's a simple loop with proper callback invocation and context management, making it one of the most straightforward array methods to implement.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code