Mastering JavaScript Iteration: Patterns for Arrays

A deep dive into array iteration in JavaScript, covering traditional index loops, for...of, forEach, map, and practical patterns. Learn why 'javascript for i in array' is not ideal and how to choose the right method for readability, performance, and correctness.

JavaScripting
JavaScripting Team
·5 min read
Array Iteration Patterns - JavaScripting

Understanding iteration in JavaScript

When you need to traverse an array, you have several patterns to choose from. The archetype you often hear in beginner material is the idea of a "javascript for i in array" loop; in practice, that exact syntax is not recommended for arrays because for...in enumerates properties and can include inherited keys. The preferred approaches are explicit index loops, for...of, and higher-order functions like forEach and map. Below are concrete examples showing how to iterate while exposing index, value, or both:

JavaScript
// Traditional index-based loop const arr = [10, 20, 30]; for (let i = 0; i < arr.length; i++) { console.log(i, arr[i]); }
JavaScript
// for...of loop (values only) for (const value of arr) { console.log(value); }
JavaScript
// Access index and value with entries() for (const [idx, val] of arr.entries()) { console.log(idx, val); }

Why avoid the naive pattern

  • It can break with sparse arrays or non-numeric keys.
  • It may iterate over non-element properties if the array is extended.
  • It is less readable when you need both index and value.

Common variations and alternatives

  • Use Array.prototype.keys() to iterate indices:
JavaScript
for (const i of arr.keys()) { console.log(i, arr[i]); }
  • Combine with destructuring for objects:
JavaScript
const people = [{name:'Amy'},{name:'Ben'}]; for (const {name} of people) { console.log(name); }

This section sets the stage for comparing methods and choosing the most appropriate pattern for your codebase.

Related Articles