The loop FOREACH is a control structure specifically designed to traverse and access the elements of a collection in a simplified manner.
Element collections are a very useful tool that we will use every day. For example, we can store a set of numbers, texts, the items a customer has purchased, or even the functions to execute on a variable.
When working with collections, a need that we will frequently encounter is to perform an action on all elements of a collection. That’s where the FOREACH loop comes into play.
In natural language, a FOREACH loop means:
For each element of this collection 🡆 do this
Which in code would look something like the following.
foreach element in collection
{
// actions to perform on each element
}
Where,
- The collection is traversed from start to finish
- In each iteration,
element
is updated with the current element - It continues until all elements have been traversed
In each iteration, the FOREACH loop assigns the next element from the collection to the variable element
and executes the associated block of code. This repeats until all elements of the collection have been processed.
The FOREACH loop simplifies performing loops over collections, resulting in more readable and concise code. Additionally, it prevents common errors related to incorrect access to elements.
Equivalence with other loops
If we had to achieve the same behavior with a WHILE loop, for example, we would have to do something like this:
index = 0;
while(there_are_pending_elements)
{
index ++;
element = collection[index];
// actions to perform with each element
}
As we can see, this is the same behavior that we defined earlier for the FOREACH loop. But it avoids the complexity of managing indices or iterators, allowing for more readable and concise code.
Examples of FOREACH loops in different languages
The FOREACH loop is common in many programming languages. Some have a specific reserved word foreach
, while others use the word for
.
For example, in the case of C#, the syntax of a FOREACH loop is as follows:
var collection = new List<int> {1, 2, 3, 4, 5};
foreach (var element in collection) {
Console.Write(element + " ");
}
In the case of C++ (yes, it also has FOREACH!), it is similar to Java’s syntax, using the reserved word for
.
auto collection = {1, 2, 3, 4, 5};
for (auto element : collection) {
std::cout << element << " ";
}
PHP also has a reserved word for FOREACH loops,
$collection = [1, 2, 3, 4, 5];
foreach ($collection as $element)
{
echo $element . " ";
}
Java, on the other hand, uses the reserved word for
with a special syntax to perform a FOREACH loop, as follows:
var collection = new int[]{1, 2, 3, 4, 5};
for (var element : collection) {
System.out.println(element);
}
On the other hand, in Python, the FOREACH loop is done with the reserved word for
. In fact, Python does not have a FOR loop as such, it is always a FOREACH.
collection = [1, 2, 3, 4, 5]
for element in collection:
print(element)
Finally, JavaScript does not have a FOREACH block as such, defined as part of the language. This is resolved with the .forEach(...)
method, which is available as a method of the collection. Thus, we achieve the functionality of a FOREACH loop.
let collection = [1, 2, 3, 4, 5];
collection.forEach(element => {
console.log(element);
});
And similarly in TypeScript
let collection: number[] = [1, 2, 3, 4, 5];
collection.forEach(element =>
{
console.log(element);
});
As we can see, most languages have the concept of FOREACH (understood as a loop that allows us to perform an action on all elements of a collection).
Some languages like C# or PHP have a reserved word foreach
. While other languages like C++ or Java use syntax variations employing for
.
On the other hand, some languages like JavaScript, TypeScript, or Kotlin, lack a dedicated FOREACH loop in the language. Instead, they provide the functionality through a method of the collection.
In any case, the functionality and the goal are the same. Apart from syntax differences, they are basically equivalent.