Mastering the forEach Loop: A Friendly Guide
The forEach method is the cleanest way to loop through arrays in JavaScript. Learn its syntax and see how it compares to for and for...of loops.
The forEach method is the cleanest way to loop through arrays in JavaScript. Learn its syntax and see how it compares to for and for...of loops.
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.
forEach Method: A Quick OverviewEvery array in JavaScript comes with a built-in forEach method. It’s designed to make looping through items a breeze, turning what could be a chore into something delightful.
The forEach method takes a callback function with three possible arguments:
currentValue: The item currently being processed.index (optional): The position of that item in the array.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});Let’s say you have a basket of fruits:
const fruitBasket = ["banana", "pear", "guava"];You can loop through this basket with forEach like this:
fruitBasket.forEach((fruit) => { console.log(fruit);});It’s concise, readable, and just works.
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 loopfor (let fruit of fruitBasket) { console.log(fruit);}
// Using a traditional for loopfor (let i = 0; i < fruitBasket.length; i++) { console.log(fruitBasket[i]);}All three approaches get the job done, but forEach has a clear advantage: it’s easier to read and write. This makes your code more maintainable, especially as your projects grow in complexity.
forEach over for...ofBoth 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.
forEach when you want a clean, readable way to loop through arrays.for...of for when you need that tiny extra performance boost — though, in most cases, it’s not necessary.