GLM 4.5 Air

Complete Guide: Loop Through Array in JavaScript

Master JavaScript array iteration with our complete guide covering traditional for loops, forEach(), for...of, and functional methods like map(), filter(), and reduce(). Learn which method works best for your needs.

Question

How can I loop through all the entries in an array using JavaScript?

GLM 4.5 Air

How to Loop Through Array Entries in JavaScript

You can loop through all entries in a JavaScript array using several methods, including traditional for loops, the forEach() method, for...of loops, and functional methods like map(), filter(), and reduce(). Each approach has its own advantages depending on your specific use case, whether you need simple iteration, transformation, filtering, or reduction of array elements.

Contents

Traditional for Loop

The traditional for loop offers the most control over iteration and is supported in all JavaScript environments.

javascript
const fruits = ['apple', 'banana', 'cherry'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Advantages:

  • Most performant in terms of raw speed
  • Provides access to the index
  • Allows complete control over the iteration process
  • Can be used to modify the array during iteration
  • Can skip or repeat iterations with continue and break

Disadvantages:

  • More verbose than modern methods
  • Index management can lead to off-by-one errors
  • Less expressive for simple iteration needs

forEach() Method

The forEach() method executes a function once for each array element.

javascript
const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number, index) => {
  console.log(`Index ${index}: ${number}`);
});

Advantages:

  • More concise than a traditional for loop
  • Provides both the element and its index
  • Cannot accidentally skip or repeat iterations
  • Works well with arrow functions for clean syntax

Disadvantages:

  • Cannot break out of the loop early
  • Cannot modify the array while iterating (though you can modify the elements)
  • Slightly less performant than a for loop
  • Requires a callback function for each iteration

for…of Loop

The for...of loop provides a clean syntax for iterating over iterable objects like arrays.

javascript
const colors = ['red', 'green', 'blue'];

for (const color of colors) {
  console.log(color);
}

Advantages:

  • Clean and readable syntax
  • No need to manage indexes
  • Can break out of the loop with break
  • Works with any iterable object
  • Provides direct access to the element value

Disadvantages:

  • Does not provide access to the index without additional work
  • Cannot modify the array while iterating
  • Slightly less performant than a traditional for loop

Functional Methods

JavaScript provides several functional methods that iterate over arrays while performing specific operations.

map() Method

The map() method creates a new array by calling a function on every element.

javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
// doubled: [2, 4, 6, 8]

filter() Method

The filter() method creates a new array with elements that pass a test.

javascript
const ages = [12, 18, 25, 32, 47];
const adults = ages.filter(age => age >= 18);
// adults: [18, 25, 32, 47]

reduce() Method

The reduce() method reduces an array to a single value.

javascript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
// sum: 10

find() Method

The find() method returns the first element that satisfies a condition.

javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];
const user = users.find(u => u.id === 2);
// user: { id: 2, name: 'Bob' }

Advantages:

  • Expressive intent (each method has a clear purpose)
  • Immutable operations (create new arrays rather than modifying existing ones)
  • Excellent for functional programming patterns
  • Often result in more concise code
  • Chainable for complex operations

Disadvantages:

  • Can be less intuitive for beginners
  • May have performance overhead for large arrays
  • Some methods (like reduce) can be complex to understand initially

for…in Loop

The for...in loop iterates over enumerable properties of an object.

javascript
const array = ['a', 'b', 'c'];
for (const index in array) {
  console.log(array[index]);
}

⚠️ Warning: While this works for arrays, it’s generally not recommended because:

  • It iterates over all enumerable properties, not just array indices
  • The order of iteration is not guaranteed
  • It can iterate over inherited properties
  • It’s slower than other array iteration methods

Array Iterator Methods

Modern JavaScript provides iterator methods for more specialized iteration needs.

entries()

Returns an iterator with key/value pairs:

javascript
const colors = ['red', 'green', 'blue'];
const iterator = colors.entries();

for (const [index, color] of iterator) {
  console.log(`${index}: ${color}`);
}

keys()

Returns an iterator with keys:

javascript
const fruits = ['apple', 'banana', 'cherry'];
const iterator = fruits.keys();

for (const index of iterator) {
  console.log(index);
}

values()

Returns an iterator with values:

javascript
const numbers = [1, 2, 3];
const iterator = numbers.values();

for (const number of iterator) {
  console.log(number);
}

Performance Comparison

Here’s a rough comparison of iteration methods in terms of performance:

Method Performance Use Case
Traditional for loop Fastest When performance is critical and you need maximum control
for…of Fast Clean iteration over values when you don’t need indices
forEach() Medium-Fast Simple iteration with access to index and value
map/filter/reduce Slower When you need to transform, filter, or reduce the array

Note: Performance differences are usually negligible for small arrays. For large arrays (10,000+ elements), the traditional for loop may show noticeable advantages.


Best Practices

  1. Choose the right tool for the job:

    • Use for loops when performance is critical
    • Use for...of for clean value iteration
    • Use forEach() when you need the index and value
    • Use functional methods (map, filter, reduce) when you need to create a new array or reduce to a value
  2. Avoid modifying arrays while iterating:

    • This can lead to unexpected behavior or infinite loops
    • If you need to modify the array, use a traditional for loop or create a copy first
  3. Consider readability:

    • Choose the method that makes your code most readable and maintainable
    • Your colleagues (and future you) will thank you
  4. Be aware of browser support:

    • Some modern methods may not be supported in very old browsers
    • Consider using transpilation (Babel) for maximum compatibility
  5. Use destructuring for cleaner code:

    javascript
    const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
    
    // With destructuring
    users.forEach(({id, name}) => {
      console.log(`User ${name} has ID ${id}`);
    });
    

Conclusion

Looping through array entries in JavaScript can be accomplished in several ways, each with its own strengths and weaknesses. The traditional for loop offers the best performance and control, while modern methods like forEach(), for...of, and functional methods provide more expressive and concise syntax.

For most everyday use cases, for...of and forEach() provide the best balance of readability and performance. When you need to transform, filter, or reduce arrays, functional methods like map(), filter(), and reduce() are the clear choice. Remember to consider the specific needs of your application, including performance requirements and browser compatibility, when choosing an iteration method.