Node.js forEach

Node.js forEach is used to execute the provided function for each element.

In this tutorial, we will learn how to use forEach statement, with the help of examples.

Syntax – forEach

The syntax of forEach is;

let arr = [element1, element2, elementN];
arr.forEach(myFunction(element, index, array, this){  function body  });

myFunction function is executed for each element in arr. The element of array is passed as argument to the function during each iteration.

ADVERTISEMENT

Example 1 – forEach on Array of elements

In this example, we will use forEach to apply on each element of array.

index.js

let array1 = ['a1', 'b1', 'c1'];

array1.forEach(function(element) {
  console.log(element);
});

Output

Node.js forEach

Example 2 – forEach on Array of elements with external function passed as argument

In this example, we will use forEach to apply on each element of array. And we define the function separately and pass as argument to forEach.

index.js

let array1 = ['a1', 'b1', 'c1']

let myFunc = function(element) {
  console.log(element)
}

array1.forEach(myFunc)

Example 3: forEach on Array with access to Element, Index and Array

In this example, we will access index and array along with element in each iteration.

index.js

let array1 = ['a1', 'b1', 'c1']

let myFunc = function(element, index, array) {
  console.log(index + ' : ' + element + ' - ' + array[index])
}

array1.forEach(myFunc)

Output

Node.js forEach - Access element, index, array