Name

Array.forEach() — invoke a function for each array element

Availability

ECMAScript 5

Synopsis

array.forEach(f)
array.forEach(f, o)

Arguments

f

The function to invoke for each element of array.

o

An optional value on which f is invoked.

Returns

This method returns nothing.

Description

forEach() loops through the indexes of array, in ascending order, and invokes f once for each element. For an index i, f is invoked with three arguments:

f(array[i], i, array)

The return value, if any, of f is ignored. Note that forEach() does not have a return value. In particular, it does not return array.

Array Method Details

The following details apply to the forEach() method, and also to the related methods map(), filter(), every(), and some().

Each of these methods expects a function as its first argument and accepts an optional second argument. If a second argument o is specified, then the function is invoked as if it was a method of o. That is, within the body of the function, this will evaluate to o. If the second argument is not specified, then the function is invoked as a function (not a method) and this will be the global object in non-strict code or null in strict code.

Each of these methods notes the length of array before it begins looping. If the invoked function appends new elements to array, those newly-added elements will not be looped over. If the function alters existing elements that have not yet been looped over, it is the altered values that will be passed.

When invoked on sparse arrays, these ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.