Easy Tutorial
❮ Jsref Toprecision Prop Style Textalignlast ❯

JavaScript forEach() Method

JavaScript Array Object

Example

List each element of the array:

Output result:

index[0]: 4
index[1]: 9
index[2]: 16
index[3]: 25

Definition and Usage

The forEach() method is used to call a function for each element in the array.

Note: forEach() does not execute the callback function for empty arrays.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method Chrome IE Firefox Safari Opera
forEach() Yes 9.0 1.5 Yes Yes

Syntax

array.forEach(callbackFn(currentValue, index, arr), thisValue)

Parameters

Parameter Description
callbackFn(currentValue, index, arr) Required. The function to execute for each element. <br>Function parameters: <br> - currentValue: Required. The current element. <br> - index: Optional. The index of the current element. <br> - arr: Optional. The array object the current element belongs to.
thisValue Optional. A value passed to the function to be used as its this value. <br>If this parameter is empty, undefined is passed as its this value.

Other syntax formats:

// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)

Technical Details

Return Value: undefined
JavaScript Version: ECMAScript 3
--- ---

More Examples

Example

Calculate the sum of all elements in the array:

Example

Multiply all values in the array by a specific number:


forEach() and continue/break

forEach() does not support continue and break statements natively. You can achieve similar effects using some and every.

Using the return statement to simulate the continue keyword:

continue Implementation

Example

var arr = [1, 2, 3, 4, 5];

arr.forEach(function (item) {
    if (item === 3) {
        return;
    }
    console.log(item);
});

break Implementation

Example

var arr = [1, 2, 3, 4, 5];

arr.every(function (item) {
    console.log(item);
    return item !== 3;
});

JavaScript Array Object

❮ Jsref Toprecision Prop Style Textalignlast ❯