Implement Array.forEach

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Implement Array.forEach

Approach

Loop through the array and invoke the callback with (element, index, array) for each item. Unlike map, forEach returns undefined and is used purely for side effects. The implementation does not collect return values.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Array Polyfill

Why It Works

forEach provides a cleaner syntax than a for loop for executing side effects on each element. It always iterates the entire array and cannot be short-circuited with break or return.

Updated Feb 2026