Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.forEach

Runs a function for every element of an array.

Available since: ES5

Syntax

array.forEach(callbackFn)

Parameters

ParameterTypeDescription
callbackFnFunctionA function that receives the element, its index and the whole array.

Return value

undefinedThe method returns nothing.

Examples

An action for each element:

['tea', 'coffee'].forEach((item) => {
  console.log(item);
});

Output:

tea
coffee

The function receives the index as its second argument:

['tea', 'coffee'].forEach((item, index) => {
  console.log(index + 1 + '. ' + item);
});

Output:

1. tea
2. coffee

Notes

forEach() cannot be stopped early: break does not work in it. Use for...of when you need to exit the loop.

See also

Related recipes

In the tutorial

  • Iterating over arrays — How to go through every element of an array in JavaScript: the for loop, for...of, forEach and entries.

Thanks for reading!

Donate to the site — we work hard for you.