Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Array.prototype.forEach()

BaselineWidely available

TheforEach() method ofArray instances executes a provided function oncefor each array element.

Try it

const array1 = ["a", "b", "c"];array1.forEach((element) => console.log(element));// Expected output: "a"// Expected output: "b"// Expected output: "c"

Syntax

js
forEach(callbackFn)forEach(callbackFn, thisArg)

Parameters

callbackFn

A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The arrayforEach() was called upon.

thisArgOptional

A value to use asthis when executingcallbackFn. Seeiterative methods.

Return value

None (undefined).

Description

TheforEach() method is aniterative method. It calls a providedcallbackFn function once for each element in an array in ascending-index order. Unlikemap(),forEach() always returnsundefined and is not chainable. The typical use case is to execute side effects at the end of a chain. Read theiterative methods section for more information about how these methods work in general.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots insparse arrays.

TheforEach() method isgeneric. It only expects thethis value to have alength property and integer-keyed properties.

There is no way to stop or break aforEach() loop other than by throwing an exception. If you need such behavior, theforEach() method is the wrong tool.

Early termination may be accomplished with looping statements likefor,for...of, andfor...in. Array methods likeevery(),some(),find(), andfindIndex() also stops iteration immediately when further iteration is not necessary.

forEach() expects a synchronous function — it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) asforEach callbacks.

js
const ratings = [5, 4, 5];let sum = 0;const sumFunction = async (a, b) => a + b;ratings.forEach(async (rating) => {  sum = await sumFunction(sum, rating);});console.log(sum);// Naively expected output: 14// Actual output: 0

To run a series of asynchronous operations sequentially or concurrently, seepromise composition.

Examples

Converting a for loop to forEach

js
const items = ["item1", "item2", "item3"];const copyItems = [];// beforefor (let i = 0; i < items.length; i++) {  copyItems.push(items[i]);}// afteritems.forEach((item) => {  copyItems.push(item);});

Printing the contents of an array

Note:In order to display the content of an array in the console,you can useconsole.table(), which prints a formattedversion of the array.

The following example illustrates an alternative approach, usingforEach().

The following code logs a line for each element in an array:

js
const logArrayElements = (element, index /*, array */) => {  console.log(`a[${index}] = ${element}`);};// Notice that index 2 is skipped, since there is no item at// that position in the array.[2, 5, , 9].forEach(logArrayElements);// Logs:// a[0] = 2// a[1] = 5// a[3] = 9

Using thisArg

The following (contrived) example updates an object's properties from each entry in thearray:

js
class Counter {  constructor() {    this.sum = 0;    this.count = 0;  }  add(array) {    // Only function expressions have their own this bindings.    array.forEach(function countEntry(entry) {      this.sum += entry;      ++this.count;    }, this);  }}const obj = new Counter();obj.add([2, 5, 9]);console.log(obj.count); // 3console.log(obj.sum); // 16

Since thethisArg parameter (this) is provided toforEach(), it is passed tocallback each time it'sinvoked. The callback uses it as itsthis value.

Note:If passing the callback function used anarrow function expression,thethisArg parameter could be omitted,since all arrow functions lexically bind thethisvalue.

An object copy function

The following code creates a copy of a given object.

There are different ways to create a copy of an object. The following is just one wayand is presented to explain howArray.prototype.forEach() works by usingObject.* utility functions.

js
const copy = (obj) => {  const copy = Object.create(Object.getPrototypeOf(obj));  const propNames = Object.getOwnPropertyNames(obj);  propNames.forEach((name) => {    const desc = Object.getOwnPropertyDescriptor(obj, name);    Object.defineProperty(copy, name, desc);  });  return copy;};const obj1 = { a: 1, b: 2 };const obj2 = copy(obj1); // obj2 looks like obj1 now

Flatten an array

The following example is only here for learning purpose. If you want to flatten anarray using built-in methods, you can useArray.prototype.flat().

js
const flatten = (arr) => {  const result = [];  arr.forEach((item) => {    if (Array.isArray(item)) {      result.push(...flatten(item));    } else {      result.push(item);    }  });  return result;};// Usageconst nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]];console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Using the third argument of callbackFn

Thearray argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first usesfilter() to extract the positive values and then usesforEach() to log its neighbors.

js
const numbers = [3, -1, 1, 4, 1, 5];numbers  .filter((num) => num > 0)  .forEach((num, idx, arr) => {    // Without the arr argument, there's no way to easily access the    // intermediate array without saving it to a variable.    console.log(arr[idx - 1], num, arr[idx + 1]);  });// undefined 3 1// 3 1 4// 1 4 1// 4 1 5// 1 5 undefined

Using forEach() on sparse arrays

js
const arraySparse = [1, 3, /* empty */, 7];let numCallbackRuns = 0;arraySparse.forEach((element) => {  console.log({ element });  numCallbackRuns++;});console.log({ numCallbackRuns });// { element: 1 }// { element: 3 }// { element: 7 }// { numCallbackRuns: 3 }

The callback function is not invoked for the missing value at index 2.

Calling forEach() on non-array objects

TheforEach() method reads thelength property ofthis and then accesses each property whose key is a nonnegative integer less thanlength.

js
const arrayLike = {  length: 3,  0: 2,  1: 3,  2: 4,  3: 5, // ignored by forEach() since length is 3};Array.prototype.forEach.call(arrayLike, (x) => console.log(x));// 2// 3// 4

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.foreach

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp