How to use forEach loops in JavaScript

Updated onbyAlan Morel
How to use forEach loops in JavaScript

When you working with arrays, one of the most common tasks is to iterate over all of the elements in the array.

In JavaScript, there are several ways to do this, including traditional for loops and while loops.

However, JavaScript has added a built-in method specifically for iterating over arrays called forEach.

In this post, we'll look at examples of how to use forEach to iterate over arrays in JavaScript.

How to use forEach loops

As mentioned before, forEach is a method that can be used to iterate over every single element in an array.

To use it, simply call it on your array and pass it a function that will be called once for each element in the array.

This callback function takes two parameters, the value of the current element and the index of the current element.

Let's start with our array:

JAVASCRIPT
const array = [1, 2, 3, 4, 5];

Now let's use forEach to iterate over the array:

JAVASCRIPT
const array = [1, 2, 3, 4, 5]; array.forEach((element, index) => { console.log(element, index); });
BASH
1 0 2 1 3 2 4 3 5 4

As expected, we were able to iterate through each individual element, and print out both the value and the index of the element.

One thing to keep in mind is that forEach cannot be broken out of because the break keyword only works inside of a loop.

Therefore, if you want to break out of a forEach loop, you'll need to use a return statement.

JAVASCRIPT
const array = [1, 2, 3, 4, 5]; array.forEach((element, index) => { if (element === 3) { return; } console.log(element, index); });
BASH
1 0 2 1 4 3 5 4

Conclusion

In this post, we've learned how to use forEach to iterate over arrays in JavaScript.

Simply call it on your array and pass it a callback function to perform some action on each element in the array.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.