Node.js – forEach() Method


The forEach() method in Node.js is used for iterating over a set of given array items. One can iterate over all the values of the array one-by-one using the forEach array loop.

Syntax

arrayName.forEach(function)

Parameters

  • function − The function takes input for the method that will be executed.
  • arrayName − Array that will be iterated.

Example 1

Create a file "forEach.js" and copy the following code snippet. After creating the file, use the command "node forEach.js" to run this code.

 Live Demo

// forEach() Demo Example

// Defining a vehicle array
const vehicleArray = ['bike', 'car', 'bus'];

// Iterating over the array and printing
vehicleArray.forEach(element => {
   console.log(element);
});

Output

C:\home
ode>> node forEach.js bike car bus

Example 2

 Live Demo

// forEach() Demo Example

// Defining a vehicle array
const array = [1,2,3,4,5,6,7,8,9];

var sum=0;

// Iterating over the array and printing
array.forEach(element => {
   sum += element;
});

console.log(sum);

Output

C:\home
ode>> node forEach.js 45

Updated on: 17-Aug-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements