Array Prototype ForEach - Problem
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.
Input & Output
Example 1 — Basic Usage
$
Input:
Array.prototype.forEach([1, 2, 3], callback)
›
Output:
Executes callback for each element
💡 Note:
forEach calls the callback function for each element: callback(1, 0, array), callback(2, 1, array), callback(3, 2, array)
Example 2 — With Context
$
Input:
Array.prototype.forEach([1, 2, 3], callback, context)
›
Output:
Executes callback with proper this binding
💡 Note:
forEach calls callback with context binding: callback.call(context, 1, 0, array), allowing 'this' to refer to context object
Example 3 — Empty Array
$
Input:
Array.prototype.forEach([], callback)
›
Output:
No callback executions
💡 Note:
Empty array results in no callback executions, forEach handles this gracefully
Constraints
- Array can be empty or contain any number of elements
- Callback function must accept currentValue, index, and array parameters
- Context parameter is optional
- Implementation should not use built-in array methods
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3,4,5] with callback function
2
Process
Iterate through each element calling callback(value, index, array)
3
Output
No return value, but callback executes for each element
Key Takeaway
🎯 Key Insight: Custom forEach implementation requires proper iteration and context binding using call() method
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code