Language: EN

programacion-bucle-foreach

The FOREACH loop

The loop FOREACH is a control structure designed specifically to iterate and access the elements of a collection in a simplified way.

Element collections are a very powerful tool that we will use every day. For example, we can store a set of numbers, texts, the items that a customer has purchased, or even the functions to be executed on a variable.

When working with collections, a need that we will frequently encounter is to perform an action on all the elements of a collection. This is 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 elemento in coleccion
{
   // actions to be performed on each element
}

Where,

  • The collection would be traversed from start to finish
  • In each iteration, element is updated with the current element
  • It continues until all elements have been traversed

programacion-bucle-foreach

In each iteration, the FOREACH loop assigns the next element of the collection to the element variable and executes the associated code block. This is repeated until all the elements of the collection have been processed.

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 be performed 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 itself.

For example, in the case of C#, the syntax of a FOREACH loop is like this,

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 a FOREACH!) it has a syntax similar to Java, 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(number);
}

On the other hand, Python performs the FOREACH loop with the reserved word for. In fact, Python does not have a FOR loop as such, it is always a FOREACH loop.

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 using the .forEach(...) method, which is available as a collection method. This way, we can 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 a FOREACH loop, which allows us to perform an action on all the elements of a collection.

Some languages like C# or PHP have a reserved word foreach. While other languages like C++ or Java use variations of syntax using for.

On the other hand, some languages like JavaScript, TypeScript, or Kotlin, do not have a FOREACH loop of their own. Instead, they provide the functionality through a collection method.

In any case, the functionality and objective are the same and, apart from syntax differences, they are basically equivalent.

The FOREACH loop simplifies looping over collections, resulting in more readable and concise code. It also avoids common errors related to incorrect access to elements.

It is widely used in situations where it is necessary to traverse and process all the elements of a collection, such as searching, filtering, transforming, or performing calculations on the elements.