const - JS | lectureWorking With Arrays

Looping Arrays - forEach

Working With Arrays

In this lecture, we will learn how to use the forEach method to loop over an array. We have already learned how to loop over an array using the for-of loop, but the forEach method is fundamentally different.

Let's consider the below array which represents the different movements in a bank account.

script.js
const movements = [644, -812, 932, 3400, -731, -553, 1737];

We will start by looping over the movements array and printing a message for each movement. So, the positive values will represent deposits and the negative values withdrawals. Let's first loop using the for-of loop just so that we can compare it with the forEach loop.

script.js
for (const movement of movements) {
  if (movement > 0) {
    console.log(`Deposit of ${movement}`);
  } else {
    console.log(`Withdrawal of ${Math.abs(movement)}`);
  }
}

FOR OF

Let's now learn how to use the forEach method to achieve the same result in an easier way (in my opinion).

script.js
movements.forEach(function() {    // do something
})

The forEach method, in this case, is a higher order function, as we learned in the previous lectures. And it requires a callback function to tell it what to do. Remember that we are not calling the callback function ourselves. What the forEach method does is to loop over the array, and in each iteration, it will execute the provided callback function.

Also, as the forEach method calls the callback function in each iteration, it will pass in the current element of the array as an argument.

script.js
/**
 * The argument can have any name, just decided to name it movement
 * because that's what we had in the for-of loop
*/
movements.forEach(function(movement) {    // do something
})

The function body, in this case, is the same as the one in the for-of loop.

script.js
movements.forEach(function (movement) {
  if (movement > 0) {    console.log(`Deposit of ${movement}`);  } else {    console.log(`Withdrawal of ${Math.abs(movement)}`);  }});

Let's now move on and learn more stuff about the forEach method, because we are not yet done. So what if we needed access to a counter variable in the forEach method? Just like we can access the current index of the array in the for-of loop. Just as a reminder, we could access the current index of the array in the for-of loop by using the entries method on the array we were looping over.

script.js
for (const [index, movement] of movements.entries()) {
  if (movement > 0) {
    console.log(`${index + 1} Deposit of ${movement}`);
  } else {
    console.log(`${index + 1} Withdrawal of ${Math.abs(movement)}`);
  }
}

FOR EACH INDEX

Let's now do the same thing using the forEach method. And fortunately, it's a lot easier to access the current index. To understand how it works, we need to remember once more that it is the forEach method that calls the callback function in each iteration. And while calling it, it also passes in the current element of the array, but actually, that's not all it passes in. In fact, forEach passes in the current element, the index, and the entire array we are looping. Hence, we can specify them in our parameter list.

script.js
/**
 * 1 - You can just specify the current element (movement) as we've been doing
 *     or everything (movement, index, movements) if you need to access them.
 * 2 - As mentionned above, the parameter names do not matter. What matters is the order.
*/
movements.forEach((movement, index, array) => {  // do something
})

Now add the function body and run the code.

script.js
movements.forEach((movement, index) => {
  if (movement > 0) {
    console.log(`${index + 1} Deposit of ${movement}`);
  } else {
    console.log(`${index + 1} Withdrawal of ${Math.abs(movement)}`);
  }
}

To finish, you are certainly asking yourself when you should use forEach and when you should use the for-of loop. Well, one fundamental difference between the two of them is that you cannot break out of a forEach loop. The continue and break statements do not work in a forEach loop. Instead, forEach will always loop over the entire array, and there is nothing you can do about it.

So if you really need to break out of a loop, then you have to keep using the for-of loop, but other than that, it really comes down to your personal preference, just like so many other things in JavaScript.