Table of Contents
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:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
Now let's use forEach to iterate over the array:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
array.forEach((element, index) => {
console.log(element, index);
});
BASH1 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.
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
array.forEach((element, index) => {
if (element === 3) {
return;
}
console.log(element, index);
});
BASH1 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!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Managing PHP Dependencies with Composer
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
Getting Started with Deno
How to deploy a Node app using Docker
Getting Started with Sass
Getting Started with Handlebars.js
Getting Started with Moment.js
Learn how to build a Slack Bot using Node.js
