The forEach
loop is a control structure in JavaScript that makes it easy to iterate over elements of a collection or data sequence (such as arrays or sets).
In JavaScript, this loop is performed through the method forEach()
, which is available in collections (actually, in iterable elements).
The forEach
loop offers several advantages over other traditional loops.
- The syntax of the
forEach
loop is clearer and simpler. - By not relying on indices, it reduces the likelihood of making errors when accessing elements of the collection.
Basic Syntax
The basic syntax of a forEach
loop in JavaScript is as follows:
collection.forEach((element) => {
// Code to execute for each element in the collection
});
- Collection: This is the collection from which the elements will be iterated.
- Element: This is the name of the variable that represents each element in the iteration.
- Instructions to execute: Here, the instructions that are executed in each iteration are specified.
Let’s see it with a simple example where we use a forEach
loop to iterate over an array of numbers:
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
This forEach
loop will print each number in the numbers
array on a separate line.
Using Arrow Functions with forEach
It is also possible to use Arrow Functions instead of anonymous functions in the forEach
syntax (in fact, it is very common).
array.forEach((element) => {
// Code to execute for each element
});
The previous example using arrow functions would look like this:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number);
});
Immutability of the Collection
One of the limitations of the forEach
loop is that it does not allow modifying the collection that is being iterated directly.
If we try to add or remove elements from the collection within the forEach
loop itself, it will usually behave erratically 😉.
For example:
let numbers = [1, 2, 3, 6, 7, 8];
numbers.forEach((num, index) => {
if (num > 5) {
numbers.splice(index, 1); // We try to remove elements from the collection
}
});
console.log(numbers); // [1, 2, 3, 7] this is not correct
In this example,
- We would expect to remove the values
>5
, and therefore get[1, 2, 3]
- However, we get
[1, 2, 3, 7]
- By modifying the collection with splice, the positions of the elements have changed, causing forEach to behave erratically.
When you need to modify the collection during iteration:
- You can use other loops like for or while.
- You can create a copy of the collection (and work on it).
let numbers = [1, 2, 3, 6, 7, 8];
// We make a copy of the array to iterate over it
let copyNumbers = [...numbers];
copyNumbers.forEach((num, index) => {
if (num > 5) {
// Remove the number from the original collection
numbers.splice(numbers.indexOf(num), 1);
}
});
console.log(numbers); // [1, 2, 3] now it's correct
Practical Examples
Iterating over a list of numbers
Suppose we have a list of integers and we want to print each of them to the console. Using the forEach
loop, the code would be as follows:
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
Iterating over an array of strings
If we have an array of strings and want to perform some operation on each of them, the forEach
loop is the ideal option. For example, if we want to convert all strings to uppercase, we can do it as follows:
let names = ["Juan", "María", "Pedro"];
names.forEach(function(name) {
console.log(name.toUpperCase());
});
Sum of elements in a list
let numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(function(number) {
sum += number;
});
console.log(`The sum of the numbers is: ${sum}`);
This forEach
loop sums all the elements in the numbers
list.
Searching for an element in an array
let numbers = [10, 20, 30, 40, 50];
let search = 30;
let found = false;
numbers.forEach(function(number) {
if (number === search) {
found = true;
}
});
if (found) {
console.log(`The number ${search} is in the array.`);
} else {
console.log(`The number ${search} is not in the array.`);
}
This forEach
loop searches for a specific number in the numbers
array and determines if it is present.
These examples are intended to show how to use the forEach
loop. It does not mean that it is the best way to solve the problems they address. Usually, there are better alternatives.