skip to content
Dev Journal

Mastering the forEach Loop: A Friendly Guide

/ 2 min read

Loops are fundamental part of programming, and when it comes to arrays in JavaScript, the forEach method is your best friend. It’s like the Swiss Army knife of loops—versatile, easy to use, and super readable.

The forEach Method: A Quick Overview

Every array in JavaScript comes with a built-in forEach method. It’s designes to make looping through items a breeze, turning what could be a chore into something delightful.

The Simple Syntax

The forEach method takes a callback function with three possible arguments:

  1. currentValue: The item currently being processed.
  2. index (optional): The position of that item in the array.
  3. array (optional): The array you’re looping over.

Most of the time, you’ll only care about the currentValue. Here’s how it looks in action:

array.forEach(currentValue => {
// Do something with currentvalue
})

A Practical Example

Let’s say you have a basket of fruits:

const fruitBasket = ["banana", "pear", "guava"]

You can loop through this baasket with forEach like this:

fruitBasket.forEach(fruit => {
console.log(fruit)
})

It’s concise, readable, and just works.

Comparing forEach with for...of and for loops.

You might be wondering how forEach stacks up against other loop types like for...of and the traditional for loop. Let’s take a quick look:

// Using for...of loop
for (let fruit of fruitBasket) {
console.log(fruit)
}
// Using a traditional for loop
for (let i = 0; i < fruitBasket.length; i++) {
console.log(fruitBasket[i])
}

All three approaches get the job done, but forEach has a clear advantages: it’s easier to read and write. THis makes your code more maintainable, especially as your projects grow in complexity.

When to Choose forEachover for...of

Both forEach and for...of are great for looping through arrays. However, forEach shines in its simplicity and readability, making it a gateway to mastering more advanced array methods like map, filter, and reduce.

The for...of loop might offer slightly better performance in certain situations, but for most use cases, the difference is negligible. So, unless you’re chasing micro-optimizations, forEach is usually the way to go.

Wrapping Up

  • Use forEaach when you want a clean, readable way to loop through arrays.
  • It’s great stepping stone to more advanced array methods.
  • Reserve for...of for when you need that tiny extra performance boost—through, in most cases, it’s not necessary.