How to use forEach loops in JavaScript
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!
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Getting Started with Deno
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js