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


#1

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