Skip to main content

Array Prototype ForEach - Solution & Explanation

EasyPremiumFree on FleetCode4 min read
Practice this problem

Problem Statement

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.

 

Example 1:

Input: 
arr = [1,2,3], 
callback = (val, i, arr) => arr[i] = val * 2, 
context = {"context":true}
Output: [2,4,6]
Explanation: 
arr.forEach(callback, context)  
console.log(arr) // [2,4,6]

The callback is executed on each element of the array.

Example 2:

Input: 
arr = [true, true, false, false], 
callback = (val, i, arr) => arr[i] = this, 
context = {"context": false}
Output: [{"context":false},{"context":false},{"context":false},{"context":false}]
Explanation: 
arr.forEach(callback, context) 
console.log(arr) // [{"context":false},{"context":false},{"context":false},{"context":false}]

The callback is executed on each element of the array with the right context.

Example 3:

Input: 
arr = [true, true, false, false], 
callback = (val, i, arr) => arr[i] = !val, 
context = {"context": 5}
Output: [false,false,true,true]

 

Constraints:

  • arr is a valid JSON array
  • context is a valid JSON object
  • fn is a function
  • 0 <= arr.length <= 105

Approach Overview

Problem Overview: Implement Array.prototype.forEach. The method receives a callback function and executes it once for every element in the array. The callback typically receives (element, index, array) and the method returns undefined.

Approach 1: Simple Iterative Implementation (O(n) time, O(1) space)

The most direct solution iterates through the array using a standard for loop. For each index i, call the provided callback with the current value, index, and the array itself: fn(this[i], i, this). The key idea is that the method runs exactly once per element, so a single pass over the array is sufficient. No extra data structures are required, which keeps space usage constant. This mirrors how many built-in array iteration utilities work internally.

Inside the prototype method, this refers to the array instance that called forEach. A loop from 0 to this.length - 1 ensures every element is processed in order. After executing the callback for each element, the function implicitly returns undefined, matching the behavior of the native implementation. Time complexity is O(n) because each element is visited once, and space complexity remains O(1).

Approach 2: Spec‑Compliant Iteration with Sparse Array Handling (O(n) time, O(1) space)

A more accurate implementation follows JavaScript's behavior for sparse arrays. Some arrays contain "holes" where an index exists in the range but no value is stored. To match native behavior, check if (i in this) before executing the callback. This prevents invoking the function for missing elements. The callback is then invoked with fn.call(thisArg, this[i], i, this) if a context parameter is provided.

This approach still performs a single linear scan across the array. The difference lies in correctly handling edge cases defined in the JavaScript specification. It also demonstrates how prototype methods work in core language fundamentals, particularly how functions interact with this and array indices.

Recommended for interviews: Interviewers usually expect the simple linear iteration approach. Showing a clean for loop that calls the callback with the correct arguments demonstrates understanding of prototypes and array iteration. Mentioning sparse array handling and thisArg support shows deeper knowledge of JavaScript internals.

Solution

Code

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Simple Iterative ImplementationO(n)O(1)Best for interviews and most implementations where every array element should trigger the callback
Spec‑Compliant Iteration (Skip Sparse Elements)O(n)O(1)When matching native JavaScript behavior, including sparse arrays and optional callback context

Video Solution

LeetCode 238. Product of Array Except Self (Solution Explained) • Nick White • 112,644 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Array Prototype ForEach easy or hard?
Array Prototype ForEach is considered an easy problem. The core logic is a simple linear loop, but it tests understanding of JavaScript prototypes, callback invocation, and how array iteration methods behave internally.
Array Prototype ForEach Python/Java solution
This problem is specific to JavaScript because it requires extending Array.prototype. Python and Java already provide built-in iteration constructs, so the equivalent task would simply involve looping through elements rather than modifying a prototype.
How to solve Array Prototype ForEach in O(n)?
Iterate through the array using a simple for loop. For each index i, invoke the callback using fn(this[i], i, this). This ensures each element is processed once, producing an O(n) time solution with constant extra space.
What is the best approach for Array Prototype ForEach?
The best approach is a single linear iteration over the array. Use a for loop from index 0 to length - 1 and call the callback with (element, index, array). This runs in O(n) time and O(1) space and matches how the native forEach method processes elements sequentially.
Is Array Prototype ForEach asked at Google/Amazon/Meta?
Problems involving custom implementations of built-in functions appear in JavaScript-focused interviews, especially for frontend roles. Companies like Amazon, Meta, and startups often use similar questions to evaluate understanding of prototypes, callbacks, and array iteration behavior.
What data structure is used in Array Prototype ForEach?
The problem operates directly on the array data structure. The algorithm relies on sequential iteration over array indices and does not require additional structures like hash maps or stacks.
What is the time complexity of Array Prototype ForEach?
The time complexity is O(n) where n is the number of elements in the array. Each element is visited exactly once and the callback is executed once per valid index. Space complexity is O(1) since no additional data structures are required.

Ready to solve this problem?

Practice Array Prototype ForEach with our built-in code editor and test cases.

Practice on FleetCode