JavaScript forEach Loop: A Practical Guide
Use the JavaScript forEach loop to run a function for every array item. See the syntax, a simple sum example, and when a classic for loop is the better choice.


JavaScript’s “foreach” loop is one of the language’s most popular and widely used features: it lets you iterate over every element in an array and do something with each one. You’ll see it used most often when processing data and working with arrays.
For example, if we want to get the sum of all the elements in an array, we can use a foreach loop. In the example below, we create an array called “numbers” and assign the sum of all its elements to a variable called “total”:
let numbers = [1, 2, 3, 4, 5];
let total = 0;
numbers.forEach(function(number) {
total += number;
});
console.log(total); // 15
We can do the same thing with a “for” loop, but a foreach loop lets us write code that’s more readable and easier to understand. What’s more, the foreach loop isn’t limited to arrays; it works with any iterable object. For example, we can use it the same way with a “Set” object:
let mySet = new Set([1, 2, 3, 4, 5]);
let total = 0;
mySet.forEach(function(number) {
total += number;
});
console.log(total); // 15
Another important advantage of the foreach loop is that it lets us do things like change the size of the array inside the loop. For example, if we want to double every element in an array, we can use it like this:
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number, index, array) {
array[index] = number * number;
});
console.log(numbers); // [1, 4, 9, 16, 25]
The foreach loop also lets us search through arrays. For example, if we want to find all the odd numbers in an array, we can use it like this:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let oddNumbers = [];
numbers.forEach(function(number) {
if (number % 2 !== 0) {
oddNumbers.push(number);
}
});
console.log(oddNumbers); // [1, 3, 5, 7, 9]
The foreach loop is one of the most common and useful features of JavaScript. It’s used often when processing data and working with arrays, and it lets us write readable, understandable, and flexible code. That’s why, when you work with JavaScript, it’s well worth learning and applying the foreach loop.
javascript do-while loop examples
Share it if it helped


