How to execute forEach in Javascript

The forEach method in Javascript iterates over the elements of an array and calls the provided function for each element in order.

Note: forEach only works on arrays. It does not execute a function for an array without any elements.

Syntax

It is written in the following form:

Description

  • array: the array on which the specified function is called.

  • forEach: the method called for the array with the required parameters.

  • function(currentValue, index, arr): the function with its parameters which is required to run for each element of the array.

    • currentValue: the value of the current element.

    • index: the index of the current element being processed.

    • arr: the array object on which function was called.

  • thisValue: value to be used as the function’s this value when executing it. “undefined” is passed if this value is not provided.

Note: index, arr and thisValue are all optional parameters.

Flow Diagram
Flow Diagram

Example

Here’s an example implementing forEach in Javascript:

var arr = ['Wall-E', 'Up', 'Coco'];
arr.forEach(function(item) {
console.log(item);
})

Explanation

In the code above, the forEach() method calls the provided function for each element of arr in order. item is used to store the current value and as a result, all the elements of the array are displayed on to the console one by one.

No optional parameters have been passed in this case. The code below uses optional parameters.

var arr = [5,4,8,7];
arr.forEach(function(item,index,arr) {
console.log("item: " + item + " at index: " + index + " in the array: " + arr);
})
Copyright ©2024 Educative, Inc. All rights reserved