Array iteration in Javascript

When iterating over arrays in JavaScript, you can use a traditional for loop or the modern .forEach() method. Both have their use cases, advantages, and trade-offs.

Here’s a comparison:
for Loop

const array = [1, 2, 3];
for (let i = 0; i < array.length; i++) {
    console.log(array[i]);
}
  • How it works: Iterates using an index (i) to access array elements.
  • Pros:
    • Allows flexible control over the iteration (e.g., you can break early, skip elements, or iterate backward).
    • Works with await in asynchronous loops.
    • Can iterate over arrays with sparse elements (e.g., arrays with undefined slots).
  • Cons:
    • Requires manual index management, which can be error-prone.
    • More verbose compared to .forEach().

Here’s a comparison:
.forEach() Method

const array = [1, 2, 3];
array.forEach((element) => {
    console.log(element);
});
  • How it works: Executes a provided callback function once for each array element.
  • Pros:
    • Cleaner and more concise for iterating through all elements.
    • Reduces boilerplate by avoiding manual index management.
    • Perfect for operations where you donโ€™t need to break out early.
  • Cons:
    • No breaking or early exit (use a for loop or .some()/.every() for that).
    • Cannot work with await directly in an asynchronous context.

When to Use

  • for Loop: When you need full control over iteration (e.g., breaking, skipping elements, or iterating in reverse).
  • .forEach(): When you need a clean, functional approach for iterating through all elements without breaking.

Conclusion

Use .forEach() for straightforward array iterations for cleaner and more readable code. Opt for for loops when more control or asynchronous behavior is required.

ย 

Author: Danyal
I'm a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.