Introduction
The forEach()
method is one of many that can be used to loop through the contents of an array and show each element successively. It has the distinct qualities that set it apart from other techniques of iterating over arrays, meaning it's up to you to select which method to employ based on what you're doing.
In this guide, you'll learn how to use the
forEach()
method and how it works using actual code examples. We'll also compare theforEach()
method andfor
loop so you can differentiate between two of them and know when to choose one over the other.
Syntax and Parameters
The forEach()
method has a very straightforward syntax:
forEach(callback(currentElement, index, arr), thisValue);
As a parameter, it accepts a callback
function and runs it for each entry in the array. This callback
function takes three arguments - the currentElement
(required), its index
(the index
of the currentElement
), and the array (arr
) to which the element belongs. Finally, the thisValue
(optional) parameter will be utilized as the value of this
in the callback
.
Note: The only required parameter is currentElement
, which represents the value of the array's elements. The index
and currentElement
arguments will be the ones you'll be using the most.
How To Use JavaScript forEach() Method
Let's take a look at the forEach()
method in action. As we've stated before, you can use it to iterate an array and apply a callback function to each element of that array. In this section, we'll explain how to declare an appropriate callback function and how to utilize each of its parameters.
In earlier versions of JavaScript, prior to ES6, you should declare a callback function as follows:
const ages = [20, 28, 19, 56];
const newAges = [];
ages.forEach(function (age) {
newAges.push(age + 5);
});
console.log(newAges);
// Output: [25, 33, 24, 61]
Alternatively, you could define the callback function somewhere outside the forEach()
method and call it using the following syntax:
const ages = [20, 28, 19, 56];
const newAges = [];
ages.forEach(increaseAgeBy5);
function increaseAgeBy5(age) {
newAges.push(age + 5);
}
console.log(newAges);
// Output: [25, 33, 24, 61]
Both of those are pretty readable and neat ways to use a forEach()
method, but we can simplify the syntax furthermore. Since ES6, we can define a callback function as an arrow function:
const ages = [20, 28, 19, 56];
const newAges = [];
ages.forEach((age) => {
newAges.push(age + 5);
});
console.log(newAges);
// Output: [25, 33, 24, 61]
Or, you can collapse the function down to just:
const ages = [20, 28, 19, 56];
const newAges = [];
ages.forEach((age) => newAges.push(age + 5));
console.log(newAges);
// Output: [25, 33, 24, 61]
The index Parameter
The index
is an optional parameter that can be used to assess the position of an element in the original array. For example, we could display both the position and the value of the element:
const courses = ['Biology', 'Mathematics', 'Chemistry', 'Physics'];
courses.forEach(function (course, index) {
console.log(index + ': ' + course);
});
This results in:
0: Biology
1: Mathematics
2: Chemistry
3: Physics
The array Parameter
The array
parameter references the original array itself. It's an optional parameter that you'll generally use relatively rarely, since you already have access to each individual element and can run operations on them. If we pass it as a parameter of console.log()
, the whole array will be printed once for each element in the array:
const courses = ['Biology', 'Mathematics', 'Chemistry', 'Physics'];
courses.forEach(function (course, index, array) {
console.log(array);
});
This results in:
[ 'Biology', 'Mathematics', 'Chemistry', 'Physics' ]
[ 'Biology', 'Mathematics', 'Chemistry', 'Physics' ]
[ 'Biology', 'Mathematics', 'Chemistry', 'Physics' ]
[ 'Biology', 'Mathematics', 'Chemistry', 'Physics' ]
Common JavaScript forEach() Examples
With the introduction out of the way - let's dive into a couple of common use cases of the forEach()
method. In this section, we'll show how to loop through an array of objects and how to calculate the sum of all elements in an array - though, you can define any arbitrary callback function.
How to Loop Through an Array of Objects by Value
Hands down - the most common use case of the forEach()
method is to print out each element (or some of their fields) of an array:
const students = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Stephen', lastName: 'Matt' },
{ firstName: 'Abigail', lastName: 'Susu' },
];
students.forEach((student) => {
console.log(`${student.firstName} ${student.lastName}`);
});
This results in:
John Doe
Stephen Matt
Abigail Susu
How to Sum Array Elements or Their Fields
Let's continue by explaining how we could add all the items in an array and display the sum
:
const students = [
{ firstName: 'John', lastName: 'Doe', tuition: 5000},
{ firstName: 'Stephen', lastName: 'Matt', tuition: 7500 },
{ firstName: 'Abigail', lastName: 'Susu', tuition: 6000 },
];
sum = 0;
students.forEach((student) => {
sum += student.tuition;
});
console.log(sum);
// Output: 18500
forEach() Method vs for Loop
JavaScript provides us a couple of ways to iterate over elements of an array - most notably the for
loop and forEach()
method. Both of them work similarly and, at the end of the day, are pretty equivalent in terms of performance. There are only a couple of differences between them, so, to help you choose which one to use, we'll cover those differences in this section.
The Scope of Variable Names
The forEach()
method has a function scope - it keeps all variable names inside the scope of its callback function. If you assign a variable outside the forEach()
method and use it within the loop, if there's a conflict (same variable name) - the one from within the callback function is used. For example, suppose we create a student
variable and assign Joy
to it. If we were looping through the students, each signified as a student
, we'd have a conflict of variable names:
const student = 'Joy';
const students = ['Mark', 'Jane', 'John', 'Sarah'];
students.forEach((student) => {
console.log(student);
// Output: "Mark" "Jane" "John" "Sarah"
});
console.log(student);
// Output: "Joy"
It's not a good practice to use the same variable name multiple times and it just adds to the confusion - but it's worth noting that forEach()
has a function scope.
Handling Missing Elements
A for
loop and forEach()
method handle missing elements differently. Suppose we have an array in which some elements are missing:
const students = ['Mark', , 'Jane', 'John', , 'Sarah'];
Taking a look at the array above, you will notice some elements are missing (an infrequence in the students
array). Firstly, let's loop over the students
array with the for
loop to see how it handles missing values:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
const students = ['Mark', , 'Jane', 'John', , 'Sarah'];
const studentsList = [];
for (let i = 0; i < students.length; i++) {
studentsList.push(students[i]);
}
console.log(studentsList);
// Output: ["Mark",undefined,"Jane","John",undefined,"Sarah"]
In the code snippet above, you will notice we are getting an undefined
value on the first and the fourth index - students[1]
and students[4]
. The for
loop treats missing elements as undefined
values.
Now, let's take a look at how the forEach()
method treats missing values in the students
array:
const students = ['Mark', , 'Jane', 'John', , 'Sarah'];
const studentsList = [];
students.forEach(function (student) {
studentsList.push(student);
});
console.log(studentsList);
// Output: ["Mark","Jane","John","Sarah"]
forEach()
skips the missing values slot and moves on!
Clean and Readable Code
It's totally up to you to decide which way of looping through an array gives cleaner and more readable code. The forEach()
method certainly has a more concise syntax, therefore it is generally considered to be more appropriate if the code readability is high on a priority list.
In this section, we'll give you example code snippets and let you decide which method for looping arrays is easier to read and understand.
Suppose we have an array of students. Each student has its name and an array of courses they attend:
const students = [
{ name: 'John', courses: ['Maths', 'English', 'Physics'] },
{ name: 'Sarah', courses: ['Chemistry', 'Maths', 'Computer Science'] },
];
Let's assume we want to display each student's name and each course that an individual student attends.
We can achieve that by using two for
loops. The first loop iterates over all students and logs the student's name. The second one iterates over all courses current student attends and logs them one by one:
for (let i = 0; i < students.length; i++) {
let student = students[i];
console.log(student);
for (let k = 0; k < student.courses.length; k++) {
let subject = student.courses[k];
console.log(subject);
}
}
The for
loop requires you to access the array using temporary i
and k
variables, and then access each element using the square bracket notation. This might seem messy and can add a lot of confusion to your code, as it is not straightforward to grasp compared to the forEach()
method:
students.forEach((student) => {
console.log(student);
student.courses.forEach((subject) => {
console.log(subject);
});
});
The forEach()
method helps us get rid of the temporary counter variables, making code a lot easier to read and understand. This method uses a callback
function and applies it to each element in the array, meaning we don't need to use a bracket notation to get each element.
Break Out of a Loop
So far, we've essentially only highlighted examples in favor of the forEach()
method. But one distinct advantage of the for
loop is its ability to exit a loop early if necessary.
For example, assume you want to return just one student named Sarah from the students
array. You need to iterate over each student in the array, check if its name is Sarah, and break out of the loop if the student is found.
You might think you can use both for
loop and forEach()
method to iterate over the students
array. But, in fact, if you try to use break
inside of the forEach()
method, it will throw a SyntaxError
.
Therefore, if you need to break out of the loop, you probably should use a for
loop:
const students = ['Mark', 'Jane', 'Sarah', 'John', 'Sarah'];
for (let i = 0; i < students.length; i++) {
if (students[i].name === 'Sarah') {
console.log(`>> ${students[i].name} is the most brilliant lady in the class`);
break;
}
console.log(`> Name of the current student is ${students[i]}`);
}
This results in:
> Name of the current student is Mark
> Name of the current student is Jane
>> Sarah is the most brilliant lady in the class
Note: The same applies to return
and continue
. There is no way of braking out of a loop in the forEach()
method - not even with return
or continue
.
async/await
The forEach()
method is not compatible with async
functions. Even if you declare an async
function inside the forEach()
block, it won't behave as expected. There is no way to make async/await
work with the forEach()
method. Therefore, if you need to make your code async
compatible, use the for
loop instead!
Using forEach() With Other Data Structures
Primarily, the forEach()
method is used to loop through an array of elements. Alternatively, you can loop through other data structures - sets and maps. In this section, we'll see a couple of simple examples illustrating how to loop through both a set and a map.
How to Loop Trough a Set Using forEach()
You can iterate through the elements of a JavaScript set using the forEach()
method. For example:
const nums = new Set([11, 25, 35, 47, 25, 47]);
nums.forEach(myFunction);
function myFunction(num) {
console.log(num);
}
This results in:
11
25
35
47
Note: A Set
is a collection of items that are unique, that is, no element can be repeated.
How to Loop Trough a Map Using forEach()
You can iterate through the elements of a map using the forEach()
method, accessing the key
and value
of each entry, rather than the entry itself:
// Declaring map
const map = new Map();
// Inserting key/value pairs
map.set('greeting', 'Hello');
map.set('firstName', 'John');
map.set('lastName', 'Doe');
// Loop through with forEach
map.forEach((value, key) => {
console.log(`${key} - ${value}`);
});
This results in:
greeting - Hello
firstName - John
lastName - John
Conclusion
In this guide, we've taken a look at how JavaScript's forEach()
method works, and how we can use it to loop through elements of an array. We've taken a look at the accompanying arguments, such as currentElement
, index
, and array
that allow you to get certain elements from an array.
Finally, we've taken a look at several examples, covered the difference between the forEach()
method and the for
loop, and illustrated how to loop through other data structures (sets and maps) using the forEach()
method.