Skip to main content
Back to problems
#2804
Easy JavaScript

Array prototype foreach

89.8% acceptance
Mar 31, 2026
9
10
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.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type Callback = (
  currentValue: JSONValue,
  index: number,
  array: JSONValue[],
) => any;
type Context = Record<string, JSONValue>;

Array.prototype.forEach = function (
  callback: Callback,
  context: Context,
): void {
  for (let i = 0; i < this.length; i++) {
  callback.call(context, this[i], i, this);
  }
};

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