Array

Array.prototype.forEach

Executes a provided function once for each array element

Syntax

JavaScript
array.forEach(callbackFn, thisArg?)

Parameters

ParameterTypeDescription
callbackFn(element, index, array) => voidFunction to execute on each element
thisArganyValue to use as this when executing callbackFn

Return Value

undefined

Examples

Basic Usage
const colors = ['red', 'green', 'blue'];
colors.forEach(color => console.log(color));
// red
// green
// blue
Practical Example
const numbers = [1, 2, 3];
const doubled: number[] = [];
numbers.forEach(n => doubled.push(n * 2));
console.log(doubled); // [2, 4, 6]
Advanced Usage
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

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.