Skip to main content

forEach

The forEach() method calls a function(callBack function) and iterates over the elements of the array.

Syntax

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

// Using Callback function
forEach(callBackFn)

// Using Inline callBack function
forEach((element) { /* ... */ })
forEach(function(element, index) { /* ... */ })
forEach((element, index, array) { /* ... */ })

Parameters

  • callBackFn: The function to be executed on each element in the array. The function will have the following arguments:

    • element: The current element of the array.

    • index: The index of the element in the array.

    • array: The array on which forEach() is called.

Examples

Using inline callBack function

let array = [1, 2, 3, 4, 5, 6];
array.forEach(function (element) {
console.log(element);
// expected output: [1, 2, 3, 4, 5, 6]
});

An anonymous function can be used inside forEach() as a callBack function which print the elements of the array.

Work out

Using callBack function

let array = [1, 2, 3, 4, 5, 6];
function doForEach(element) {
console.log(element);
// expected output: [1, 2, 3, 4, 5, 6]
}
array.forEach(doForEach);

Work out

Using Arrow function

let array = [1, 2, 3, 4, 5, 6];
array.forEach((element) => console.log(element));

Work out