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 processed
  • index - The index of the current element
  • array - 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
Array.prototype.forEach VisualizationConveyor Belt (Array)12345Worker(Callback)Receives:โ€ข Current Itemโ€ข Position (Index)โ€ข Whole Belt (Array)Context(Optional)Sets 'this' valuein callback functionReturns: undefinedFor each element:1. Get current value & index2. Call callback(value, index, array)3. Apply context if provided4. Move to next element
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.
Asked in
Google 25 Meta 20 Amazon 18 Microsoft 15
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen