In JavaScript, there are several ways to loop over each element in an array. Here’s a breakdown of the most common methods, along with examples and use cases:
1. forEach()
Method
Executes a provided function once for each array element.
Best for: Iterating over elements without needing to break the loop early.
Note: Does not return a value and cannot use break
or continue
.
const fruits = ["Apple", "Banana", "Cherry"];
// Syntax:
fruits.forEach((element, index, array) => {
console.log(`Element: ${element}, Index: ${index}`);
});
// Output:
// Element: Apple, Index: 0
// Element: Banana, Index: 1
// Element: Cherry, Index: 2
2. for...of
Loop (ES6+)
Iterates over iterable objects (like arrays) using a concise syntax.
Best for: Clean, modern iteration with support for break
and continue
.
const numbers = [10, 20, 30];
for (const num of numbers) {
if (num === 20) break; // Can exit early
console.log(num);
}
// Output:
// 10
3. Traditional for
Loop
Uses an index to access elements.
Best for: Situations requiring control over the index (e.g., modifying the array mid-loop).
const colors = ["Red", "Green", "Blue"];
for (let i = 0; i < colors.length; i++) {
console.log(`Index: ${i}, Color: ${colors[i]}`);
}
// Output:
// Index: 0, Color: Red
// Index: 1, Color: Green
// Index: 2, Color: Blue
4. map()
Method
Creates a new array by applying a function to each element.
Best for: Transforming array elements (not just iterating).
const prices = [5, 10, 15];
const doubled = prices.map((price) => price * 2);
console.log(doubled); // [10, 20, 30]
Key Differences
Method | Pros | Cons |
---|---|---|
forEach() | Simple syntax, no index management. | No break /continue , skips empty slots. |
for...of | Supports break /continue , clean syntax. | No access to index unless tracked manually. |
for Loop | Full control over index and flow. | Verbose syntax. |
map() | Returns a new array, chainable. | Overkill if you don’t need a new array. |
When to Use Which
- Basic iteration:
forEach()
orfor...of
. - Early termination (e.g.,
break
):for...of
orfor
loop. - Index manipulation: Traditional
for
loop. - Transform data:
map()
.
Avoid for...in
for Arrays
The for...in
loop iterates over enumerable properties (including inherited ones), which is not ideal for arrays:
const arr = [10, 20, 30];
arr.customProp = "Oops!";
// ❌ Avoid: Includes 'customProp' and non-integer keys
for (const key in arr) {
console.log(key); // Outputs: 0, 1, 2, "customProp"
}
Async/Await with Loops
Use for...of
(not forEach()
) for asynchronous operations:
async function processArray(array) {
for (const item of array) {
await someAsyncFunction(item); // Works as expected
}
}
By choosing the right method, you can efficiently loop through arrays in JavaScript!