forEach() in JavaScript

forEach() in JavaScript

22 Aug 2024
Intermediate
129 Views
18 min read
Learn via Video Course & by Doing Hands-on Labs

JavaScript For Beginners Free Course

What is JavaScript forEach()?

The forEach() method in JavaScript loops through the array elements. This iterative method executes a predefined function once for each of the array elements in ascending index order, known as a callback function. You cannot execute the forEach() for empty array elements. forEach() always returns undefined; hence, it is not chainable like other iterative methods such as filter(), map(), etc.

In this JavaScript tutorial, we'll learn the forEach() function, including its syntax, parameters, examples, forEach() with arrays, map and sets, comparison of forEach() and for loop and more.

Read More: JavaScript Interview Questions and Answers (Fresher + Experience)

Syntax of forEach()


array.forEach(callbackFunction);
array.forEach(callbackFunction, thisValue);   

or

array.forEach(function(currentValue, index, array));     

Read More: Functions in JavaScript: User-Defined and Standard Library Functions

Parameters:

The forEach() method mainly takes two parameters; one is necessary, and the other is optional:

  1. Callback function: It holds the function to be executed once on each array element. It can take up to three parameters:
    1. currentElement: is the current array element being processed at the time the loop occurs. It is the only compulsory parameter.
    2. index: It is the index of the current element being processed.
    3. array: The original array forEach() was called upon.
  2. thisValue: It holds the context to be passed as this is to be used while executing the callback function in Javascript. This is an optional parameter.

forEach() with Arrays

We know that forEach() method iterates over array elements.

Example of displaying the array elements using forEach()


let employee = ['Sourav', 'Sakshi', 'Pradnya'];

// using forEach
employee.forEach(myFunction);

function myFunction(item) {

    console.log(item);
}

In the above code, the forEach() method takes the myFunction() function that displays each element of the employee array.

Output

Sourav
Sakshi
Pradnya

forEach() with Arrow Function

The arrow function in Javascript can be used with the forEach() method.

Example of forEach() with Arrow Function


let employee = ['Sourav', 'Sakshi', 'Pradnya'];

employee.forEach(element => {
  console.log(element);
});

You can observe that the callback function is defined using an arrow function syntax. It takes one parameter element denoting the current element of the array being processed.

Output

Sourav
Sakshi
Pradnya

Usage of Parameters passed to the Callback Function

1. Using the currentElement parameter

const employeesDetails = [
  { name: "Shailendra Chauhan", age: 50, salary: 40000, designation: "CEO" },
  { name: "Sourav Kumar", age: 30, salary: 30000, designation: "SEO" },
  { name: "Sakshi Dhameja", age: 37, salary: 3700, designation: "Mentor" },
  { name: "Pradnya", age: 27, salary: 20000, designation: "Content Writer" }
];

employeesDetails.forEach((employeeDetail) => {
  let sentence = `I am ${employeeDetail.name} an employee of ScholarHat.`;
  console.log(sentence);
});

The above JavaScript program iterates over an array of employeeDetails and logs a sentence for each employee to the console.

Output

I am Shailendra Chauhan an employee of ScholarHat.
I am Sourav Kumar an employee of ScholarHat.
I am Sakshi Dhameja an employee of ScholarHat.
I am Pradnya an employee of ScholarHat.

2. Using the index parameter

The index parameter of the callback function helps in getting the index of the array elements.


const employeesDetails = [
  { name: "Shailendra Chauhan", age: 50, salary: 40000, designation: "CEO" },
  { name: "Sourav Kumar", age: 30, salary: 30000, designation: "SEO" },
  { name: "Sakshi Dhameja", age: 37, salary: 3700, designation: "Mentor" },
  { name: "Pradnya", age: 27, salary: 20000, designation: "Content Writer" }
];

employeesDetails.forEach((employeeDetail, index) => {
  let sentence = `index ${index} : I am ${employeeDetail.name} an employee of ScholarHat.`;
  console.log(sentence);
});

The above JavaScript program iterates over an array of employeeDetails and logs a sentence for each employee along with their index to the console.

Output

index 0 : I am Shailendra Chauhan an employee of ScholarHat.
index 1 : I am Sourav Kumar an employee of ScholarHat.
index 2 : I am Sakshi Dhameja an employee of ScholarHat.
index 3 : I am Pradnya an employee of ScholarHat.

3. Using the array parameter

const employeesDetails = [
  { name: "Shailendra Chauhan", age: 50, salary: 40000, designation: "CEO" },
  { name: "Sourav Kumar", age: 30, salary: 30000, designation: "SEO" },
  { name: "Sakshi Dhameja", age: 37, salary: 3700, designation: "Mentor" },
  { name: "Pradnya", age: 27, salary: 20000, designation: "Content Writer" }
];

employeesDetails.forEach((employeeDetail, index, array) => {
  console.log(array);
});

The array parameter outputs the entire array 4 times since we have four array elements, and the iteration occurs four times.

Output

[
  {
    name: 'Shailendra Chauhan',
    age: 50,
    salary: 40000,
    designation: 'CEO'
  },
  { name: 'Sourav Kumar', age: 30, salary: 30000, designation: 'SEO' },
  {
    name: 'Sakshi Dhameja',
    age: 37,
    salary: 3700,
    designation: 'Mentor'
  },
  {
    name: 'Pradnya',
    age: 27,
    salary: 20000,
    designation: 'Content Writer'
  }
]
[
  {
    name: 'Shailendra Chauhan',
    age: 50,
    salary: 40000,
    designation: 'CEO'
  },
  { name: 'Sourav Kumar', age: 30, salary: 30000, designation: 'SEO' },
  {
    name: 'Sakshi Dhameja',
    age: 37,
    salary: 3700,
    designation: 'Mentor'
  },
  {
    name: 'Pradnya',
    age: 27,
    salary: 20000,
    designation: 'Content Writer'
  }
]
[
  {
    name: 'Shailendra Chauhan',
    age: 50,
    salary: 40000,
    designation: 'CEO'
  },
  { name: 'Sourav Kumar', age: 30, salary: 30000, designation: 'SEO' },
  {
    name: 'Sakshi Dhameja',
    age: 37,
    salary: 3700,
    designation: 'Mentor'
  },
  {
    name: 'Pradnya',
    age: 27,
    salary: 20000,
    designation: 'Content Writer'
  }
]
[
  {
    name: 'Shailendra Chauhan',
    age: 50,
    salary: 40000,
    designation: 'CEO'
  },
  { name: 'Sourav Kumar', age: 30, salary: 30000, designation: 'SEO' },
  {
    name: 'Sakshi Dhameja',
    age: 37,
    salary: 3700,
    designation: 'Mentor'
  },
  {
    name: 'Pradnya',
    age: 27,
    salary: 20000,
    designation: 'Content Writer'
  }
]

Conditionals in a forEach() Callback Function

While iterating through arrays, we can check for specific conditions by passing these conditions into our callback function.


const employeesDetails = [
  { name: "Shailendra Chauhan", age: 50, salary: 40000, designation: "CEO" },
  { name: "Sourav Kumar", age: 30, salary: 30000, designation: "SEO" },
  { name: "Sakshi Dhameja", age: 37, salary: 37000, designation: "Mentor" },
  { name: "Pradnya", age: 27, salary: 20000, designation: "Content Writer" }
];

employeesDetails.forEach(({name, salary}) => {
  if(salary >= 30000){
    console.log(name);
  }
});

The above code checks the salary of all the employees in the array and prints the one having a salary greater than 40000.

Output

Shailendra Chauhan
Sourav Kumar
Sakshi Dhameja

forEach() vs. for loop in JavaScript/for loop to forEach()

The forEach() and for loop in JavaScript resemble very much, except for some differences.

Example Illustrating for loop in JavaScript


const names = ["Sourav", "Sakshi", "Girdhar", "Amit"];
let text = ""; 

for (let i = 0, len = names.length; i < len; i++) {
  text += names[i] + " ";
}

console.log(`text: ${text}`);

In the above code, the for loop iterates over the names array, appending the current element to the text string in each iteration.

Output

text: Sourav Sakshi Girdhar Amit 

Now, we'll convert the for loop in the above code into forEach().

const names = ["Sourav", "Sakshi", "Girdhar", "Amit"];
let text = "";

names.forEach(name => {
  text += name + " ";
});

console.log(`text: ${text}`);

The forEach method iterates over the elements in the names array, and the arrow function appends each name to the text variable.

Output

text: Sourav Sakshi Girdhar Amit 

In the forEach(), you cannot use the break or continue statement to control the loop like for loop. To terminate the loop in the forEach() method, you must throw an exception inside the callback function.

forEach() with Sets


const set = new Set(["Sourav", "Sakshi", "Girdhar", "Amit"]);

set.forEach(myFunction);

function myFunction(item) {
    console.log(item);
}

Output

Sourav
Sakshi
Girdhar
Amit 

forEach() with Maps

Read More: Map in Javascript


let map = new Map();

// inserting elements
map.set('name', 'Sakshi');
map.set('designation', 'Mentor');

// looping through Map
map.forEach (myFunction);

function myFunction(value, key) {
    
    console.log(key + ': ' + value);
}

Output

name: Sakshi
designation: Mentor
Summary

We saw the forEach() function in quite detail and understood its applications through various examples. forEach() uses callback functions, which is a fundamental concept in JavaScript asynchronous programming. You need to be through with it to understand the forEach() smoothly. You can explore this topic much more in our JavaScript Programming Course.

FAQs

Q1. What is the use of forEach ()?

You should use a forEach loop when you want to do something for each element of an array, array you don't want to edit. If you want to perform something on each element of an array, you would use the map method. Example of forEach : You want to add 1 to a variable for each odd element of an array

Q2. Why use forEach instead of for js?

ForEach(function(element) { // Do something with element }); One advantage of using a forEach loop is that you don't need to manually manage the index or handle the iteration logic yourself.

Q3. What is difference between for loop and forEach?

The forEach() method is also used to loop through arrays, but it uses a function differently than the classic “for loop”. 

Q4. Can we use forEach for object?

You can use forEach() in order to iterate over all the values nested in objects in an array using JavaScript.

Take our Javascript skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Azure Developer Certification TrainingSep 14SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
ASP.NET Core Certification TrainingSep 15SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 15SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Software Architecture and Design TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
.NET Solution Architect Certification TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this