Array Prototype ForEach - Problem
Write your own version of the forEach method that enhances all arrays so you can call array.forEach(callback, context) on any array and it will execute the callback on each element.
Requirements:
- Method
forEachshould not return anything - Callback accepts these arguments:
currentValue(current element),index(current index),array(the entire array) - The
contextparameter sets thethisvalue inside the callback function - Implement without using built-in array methods
Input & Output
Example 1 — Basic Usage
$
Input:
arr = [1, 2, 3], callback = (val, idx) => console.log(val, idx)
›
Output:
Logs: 1 0, 2 1, 3 2
💡 Note:
forEach calls the callback for each element with value and index parameters
Example 2 — With Context
$
Input:
arr = ['a', 'b'], callback uses this.prefix, context = {prefix: 'Item: '}
›
Output:
Uses context.prefix in callback function
💡 Note:
The context parameter becomes 'this' inside the callback function
Example 3 — Array Parameter
$
Input:
arr = [10, 20], callback = (val, idx, array) => console.log(array.length)
›
Output:
Logs: 2, 2
💡 Note:
Third parameter gives callback access to the entire array
Constraints
- Must extend Array.prototype in JavaScript
- Callback receives (currentValue, index, array) parameters
- Context parameter sets 'this' value in callback
- Should not return any value
- Cannot use built-in array methods
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code