Why should I use .forEach() vs a for loop?

Question

Why should I use .forEach() vs a for loop?

Answer

Some benefits of for loops:

  • Control over the condition of the for loop - ex: does not have to stop at the end of the array (i < array.length), can be a different condition
  • Can use break statements in a for loop to break out of the loop early, for example:
let myArray = ['this', 'is', 'my', 'array'];

for (let i = 0; i < myArray.length; i++) {
  if (myArray[i] === 'is') {
    console.log('critera is met!');
    break; //will break out of the `for` loop early, no more iterations of loop unnecessarily 
  }
}

Some benefits of .forEach():

  • Less setup - only need to pass a function to .forEach() to execute for each element of the array
  • Easy to read, especially with more complex code
  • Less room for error, for example, we will not run into the error where we iterate over an array one too many times
2 Likes

How come that the argument of the function politelyDecline was automatically known as it was given as an argument in the politelyDecline function, how did the forEach knew that the politelyDecline had an argument and that it should fill it with veggies array?:

const veggies = [‘broccoli’, ‘spinach’, ‘cauliflower’, ‘broccoflower’];

const politelyDecline = (veg) => {

  console.log('No ' + veg + ' please. I will have pizza with extra cheese.');

}

// Write your code here:

const declineEverything = (strArray) => {

strArray.forEach(politelyDecline);

};

declineEverything(veggies);

3 Likes

This is because politelyDecline is a variable that points to a function. This means that

strArray.forEach(politelyDecline);

is equivalent to:

strArray.forEach((veg) => {console.log(‘No ’ + veg + ’ please. I will have pizza with extra cheese.’});

3 Likes

This behavior is as a result of the syntax for .forEach().
In the syntax for .forEach(), It expects to be passed a callback function which has between 1 to 3 parameters. In order for .forEach() to work it requires the callback function passed in to match this syntax.
Out of the 3 callback function parameters, only one is compulsory, which is currentValue. The other two parameters index and array can optionally be passed in.

If the callback function we supply to the .forEach() doesn’t match the syntax, it will not work as intended
:slightly_smiling_face:

3 Likes

I am actually having a bit of a hard time understanding this logic, and the explanation did not seem to clear up the confusion that I am having, and hoping for some further clarity.

I understand that the variable ‘politelyDecline’ was passed to the .forEach() as an argument, but ‘politelyDecline’ is a function that takes one argument itself. When it was passed as an argument to .forEach() we never passed it any arguments? further more how was each ‘veg’ passed through to it when it was only passed a function variable?
It is this that gets me puzzled and reading the MDN documentation does not clear this up for me, as this example of usage does not seem to be discussed.

The syntax I would have used which was incorrect for this example as per the text in the question was ‘strArray.forEach(veg => politelyDecline(veg));’

That syntax makes sense to me as .forEach parses one ‘veg’ from the array and uses the call back of the politelyDecline passing it each ‘veg’ as its parameter.

If someone is able to please better clarify how this works that would be greatly appreciated.

Iterators such as, Array.forEach() have their own internal iterator variable. The callback need only be a reference to a function object. The iterator handles the invocation of the function, once for each value in the array.

1 Like

Appreciate your time to reply.
Yes, this actually started making sense as I proceeded through that sections exercises, as the other array methods we learnt about act the same way.
I think the problem I was having is not fully understanding the documentation syntax correctly and piecing it together in my head.
Thanks again.

1 Like