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 on collections (actually, on iterable elements).
The forEach loop offers several advantages over other traditional loops.
- The syntax of the
forEachloop is clearer and simpler. - By not relying on indexes, it reduces the possibility of making errors when accessing collection elements.
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 whose elements are to be iterated.
- Element: This is the name of the variable representing each element in the iteration.
- Instructions to execute: Here, the instructions to be 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’s 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 being iterated directly.
If we try to add or remove elements from the collection inside the forEach loop itself, it will most likely go crazy 😉.
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
Iterate Over a List of Numbers
Suppose we have a list of integers and we want to print each one 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);
});
Iterate Over an Array of Strings
If we have an array of strings and we 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 = ["Luis", "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 adds all elements in the numbers list.
Search 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 it is the best way to solve the problem they address. Usually, there are better alternatives.
