Language: EN

javascript-bucle-foreach

ForEach loop in JavaScript

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