English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Others

Node.js forEach

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

Syntax - forEach

The syntax of forEach is;

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

The myFunction function executes element in arr. element is passed as a parameter to the function during each iteration, and the array is passed as a parameter to the function.

Example1:forEach on the element array

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

let array1 = ['a1', 'b1', 'c1']; 
array1.forEach(function(element) { 
  console.log(element); 
 });

Output Result

a1
b1
c1

Example2:forEach has an external function passed as a parameter on the element array

In this example, we will apply forEach to each element of the array. Then, we define the function separately and pass it as a parameter to forEach.

let array1 = ['a1', 'b1', 'c1} 
let myFunc = function(element) { 
  console.log(element) 
 } 
array1.forEach(myFunc)

Example3:Can access element, index, and array on the forEach of the array

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

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

Output Result

0 : a1 - a1
1 : b1 - b1
2 : c1 - c1