Array.prototype.forEach
Executes a provided function once for each array element
Syntax
array.forEach(callbackFn, thisArg?)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | (element, index, array) => void | Function to execute on each element |
| thisArg | any | Value to use as this when executing callbackFn |
Return Value
undefined
Examples
const colors = ['red', 'green', 'blue'];
colors.forEach(color => console.log(color));
// red
// green
// blueconst numbers = [1, 2, 3];
const doubled: number[] = [];
numbers.forEach(n => doubled.push(n * 2));
console.log(doubled); // [2, 4, 6]const map = new Map<string, number>();
['a', 'b', 'c'].forEach((char, i) => {
map.set(char, i);
});
console.log(map); // Map { 'a' => 0, 'b' => 1, 'c' => 2 }Understanding Array.prototype.forEach
The Array.prototype.forEach method in JavaScript executes a provided function once for each array element. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.
The method signature is array.forEach(callbackFn, thisArg?). It accepts 2 parameters: callbackFn, thisArg. When called, it returns undefined. Understanding when and how to use forEach() helps you write more expressive, readable code.
Common use cases for Array.prototype.forEach include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-map, array-filter, array-some, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Array.prototype.forEach is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Array.prototype.mapCreates a new array populated with the results of calling a provided function on every element in the calling array
Array.prototype.filterCreates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test implemented by the provided function
Array.prototype.someTests whether at least one element in the array passes the test implemented by the provided function
Array.prototype.everyTests whether all elements in the array pass the test implemented by the provided function
More Array Methods
Other methods in the Array object
Related Tools
More Array Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.