In JavaScript, there are multiple ways to loop through an array, each suited for different scenarios. Below is a detailed explanation of the most common methods, including examples and use cases.
1. Classic for
Loop
Iterate using an index counter.
Use Case: When you need the index or control over iteration steps.
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(`Index ${i}: ${fruits[i]}`);
}
// Output:
// Index 0: apple
// Index 1: banana
// Index 2: cherry
Pros:
- Works in all browsers (including very old ones).
- Allows breaking early with
break
or skipping withcontinue
.
2. for...of
Loop (ES6)
Iterate directly over array values.
Use Case: Simple iteration when you don’t need the index.
for (const fruit of fruits) {
console.log(fruit);
}
// Output:
// apple
// banana
// cherry
With Index:
for (const [index, fruit] of fruits.entries()) {
console.log(`Index ${index}: ${fruit}`);
}
Pros:
- Clean and readable.
- Avoids manual index management.
3. forEach()
Method
Execute a function for each element.
Use Case: Functional-style iteration without needing to break early.
fruits.forEach((fruit, index) => {
console.log(`Index ${index}: ${fruit}`);
});
// Output:
// Index 0: apple
// Index 1: banana
// Index 2: cherry
Notes:
- ⚠️ Cannot use
break
orcontinue
insideforEach
. - Returns
undefined
(does not create a new array).
4. map()
Method
Create a new array by transforming elements.
Use Case: When you need to return a modified array.
const upperCaseFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperCaseFruits); // ['APPLE', 'BANANA', 'CHERRY']
Note:
- Always returns a new array (does not mutate the original).
5. for...in
Loop (Use with Caution!)
Iterates over enumerable properties, including non-index properties.
Use Case: Rarely used for arrays (prefer for...of
or forEach
).
// Not recommended for arrays!
for (const index in fruits) {
console.log(fruits[index]);
}
Pitfalls:
- Includes inherited or custom properties if added to the array.
- Can iterate in an unexpected order.
6. while
Loop
Iterate using a condition.
Use Case: When you need complex loop control.
let i = 0;
while (i < fruits.length) {
console.log(fruits[i]);
i++;
}
7. reduce()
Method
Iterate to accumulate a single value.
Use Case: Summing values or flattening arrays.
const numbers = [1, 2, 3];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 6
8. filter()
Method
Iterate to create a subset of the array.
Use Case: Selecting elements that meet a condition.
const filtered = fruits.filter(fruit => fruit.startsWith('b'));
console.log(filtered); // ['banana']
Summary Table
Method | Returns | Use Case | Breakable? |
---|---|---|---|
for | – | Full control over iteration | Yes |
for...of | – | Simple value-based iteration | Yes |
forEach() | undefined | Functional-style iteration | No |
map() | New array | Transforming elements | No |
reduce() | Single value | Aggregating data | No |
filter() | Filtered array | Selecting elements | No |
When to Use Which?
- Need the index? Use
for
,forEach
, orfor...of
with.entries()
. - Need to break early? Use
for
orfor...of
. - Functional programming? Use
forEach
,map
, orfilter
. - Modern code? Prefer
for...of
orforEach
for readability.
Edge Cases
- Sparse Arrays:
const sparseArray = [1, , 3]; // Empty slot at index 1
sparseArray.forEach((item) => console.log(item)); // Logs 1, 3 (skips empty)
- Modifying Arrays During Iteration:
Avoid adding/removing elements mid-loop to prevent unexpected behavior.
Let me know if you’d like more examples or clarification!