a concise shot of dev knowledge
Become a Contributor
Concise shots of dev knowledge

RELATED TAGS

loop
javascript
method
foreach

How to execute forEach in Javascript

Edpresso Team

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.

svg viewer
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);
})

RELATED TAGS

loop
javascript
method
foreach
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2