Loop (for each) over an Array in JavaScript: A Detailed Guide
When working with arrays, one of the most essential tasks is iterating over their elements. There are several methods to loop through an array in JavaScript, and in this article, we’ll dive deep into these approaches, focusing on the forEach()
method as well as other alternatives.
1. Introduction to Looping Over Arrays
When working with arrays, looping through them allows you to perform operations like modifying elements, calculating sums, filtering data, or even transforming each element into a new form. JavaScript offers several built-in ways to loop through arrays, each suited for different use cases.
2. Using the forEach() Method
The forEach()
method is a built-in JavaScript function used to iterate over all elements of an array. Unlike traditional for
loops, forEach()
is more concise and functional in style.
array.forEach(function(element, index, array) {
// Your code here
});
Where –
- element: The current element being processed.
- index: The index of the current element (optional).
- array: The array that
forEach
is iterating over (optional).
let arr = [10, 20, 30, 40, 50]; arr.forEach(function(item) { console.log(item); }); /* Output: 10 20 30 40 50 */
Use Cases
- Simple iteration: Use
forEach()
when you need to loop through an array and perform an operation on each element without returning anything. - Side-effects: Ideal when you need to execute a function that does not need to return a value, such as logging or updating elements in the DOM.
Notes:
forEach()
does not return a new array. It returnsundefined
.- It cannot be stopped or broken early; all elements are always processed.
- It is slower than a traditional
for
loop in terms of performance.