JavaScriptArrays

Array.prototype.forEach()

Calls a function for every element of the array.

Returns
undefined
Changes the original
No
On this page

Example

#
JavaScript
const modules = ['HTML', 'CSS', 'JavaScript']

modules.forEach((module, index) => {
  console.log(`${index + 1}. ${module}`)
})
Console
1. HTML
2. CSS
3. JavaScript

Definition and usage

#

The forEach() method walks through the array’s elements in order and calls the given function for each one. It doesn’t return a value (always undefined), so it’s used for side effects: logging, saving, adding elements to the page.

A forEach() loop can’t be stopped with break. If you want to exit early, use a plain for...of loop or the some() or find() methods.

It doesn’t play well with await either: async functions inside forEach() aren’t waited for one after another. For sequential async operations, a for...of loop is a better fit.

Syntax

#
Syntax
array.forEach(callbackFn)
array.forEach(callbackFn, thisArg)

Parameters

#
  • callbackFn

    function (element, index, array)

    The function called for every element.
  • thisArg

    optional

    The this value inside the function.

More examples

#
forEach() always returns undefined
JavaScript
const result = [1, 2, 3].forEach((n) => n * 2)
console.log(result)
Console
undefined

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • If you’re building a new array from the results, use map() instead of forEach() with push().
  • For loops with await, and for loops you need to break out of, choose for...of.

Related entries

#

Spotted a mistake or missing an example? Write to us.