How do I loop through an array in JavaScript

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 with continue.

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 or continue inside forEach.
  • 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

MethodReturnsUse CaseBreakable?
forFull control over iterationYes
for...ofSimple value-based iterationYes
forEach()undefinedFunctional-style iterationNo
map()New arrayTransforming elementsNo
reduce()Single valueAggregating dataNo
filter()Filtered arraySelecting elementsNo

When to Use Which?

  • Need the index? Use for, forEach, or for...of with .entries().
  • Need to break early? Use for or for...of.
  • Functional programming? Use forEach, map, or filter.
  • Modern code? Prefer for...of or forEach for readability.

Edge Cases

  1. Sparse Arrays:
   const sparseArray = [1, , 3]; // Empty slot at index 1
   sparseArray.forEach((item) => console.log(item)); // Logs 1, 3 (skips empty)
  1. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *