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 forEach should not return anything
  • Callback accepts these arguments: currentValue (current element), index (current index), array (the entire array)
  • The context parameter sets the this value 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
Array Prototype forEach ImplementationINPUT: Array ExtensionArray.prototype.forEachMethod to be implemented123Sample Array: [1, 2, 3]Parameters:• callback function• context (optional)• no return valueALGORITHM: Iteration Process1Validate callback function2Start loop: i = 0 to length-13Get current element this[i]4Call callback.call(context, elem, i, this)For each iteration:callback(value, index, array)with proper context bindingRESULT: Method AvailableArray.prototype.forEach✓ Method successfully addedAvailable on all arraysUsage:[1,2,3].forEach(callback)Executes callback for eachelement with contextNo Return ValueforEach returns undefinedKey Insight:Use Array.prototype to extend all arrays with forEach method. Loop through indices and call callback.call(context, element, index, array) for proper parameter passing and context binding.TutorialsPoint - Array Prototype ForEach | Manual Loop Implementation
Asked in
Google 15 Facebook 12 Microsoft 10
23.0K Views
Medium Frequency
~15 min Avg. Time
890 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