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 Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a Deno app using Docker
How to deploy a MySQL Server using Docker
How to deploy a Node app using Docker
Getting Started with Sass
Learn how to build a Slack Bot using Node.js
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
