In which cases we must use "forEach" loop?

in référence to this hold topic :
A summary on loops
I would like to know what you think about the “forEach” loop, compared to others ?
In which case do you use it ?

All variations of a for loop do basically the same thing. forEach is an array method, so I use it when I have an array and want to loop over it but the other array methods aren’t a good fit.

You should use a forEach loop when you want to do something for each element of an array, array you don’t want to edit. If you want to perform something on each element of an array, you would use the map method.

Example of forEach :
You want to add 1 to a variable for each odd element of an array. You could do something like this :

let acc = 0;
const array = [1, 2, 3, 4, 5];
array.forEach(element => {
  if (element%2 === 0) {
    acc ++;

There may be a better way to do things, but this one is an example of forEach !

If the operation you want to do is async, it is easier to use a for … of loop

Hi Jeremy,
It’s little short :slightly_smiling_face:
So you use it rather as a last resort.
Could you please give me more details ?

I wouldn’t necessarily call it a ‘last resort’. If I have an array, I’ll probably use an array method when looping over the array. If I’m making a new array from an old one, I’ll use map or filter. If I’m condensing the array to a single value, I’ll use reduce. For other stuff, I’ll often use forEach. Though, I’m having trouble finding a fCC challenge where I’d prefer forEach over some other option.

  1. You get cleaner access to the array elements as you do not need to index into the array and you can name what the element is as it is now a function parameter.

  2. You avoid off-by-one errors because forEach does the looping for you.

  3. Because forEach uses a callback function you can put the looping action/logic inside its own function(s). This lets you move them to a different location (e.g. a utils folder) and you can name them making the code more declarative.



yes, I forgotten that
Thanks again

Thanks to all for your explanations

My suggestion:

forEach does not utilize continue and break keywords. Therefore, use forEach only and only if you want to process all elements in the array. Use while loop, when you want the iteration to stop once some condition is met and for loop for anything else.