Loop through an array in JavaScript
Use forEach for a user-friendly and straightforward iteration. Here, fruit is the array element and i the index.
Pick your weapon: Array iteration methods
Different iteration methods are available for specific tasks. To transform elements and create a new array, use map:
Dispense with manual accumulation and use reduce to calculate accumulated values:
For drawing out the seconds between acts, use filter to extract relevant elements:
For direct access to array values, the for...of loop is your mate:
Note that for...of is a tough cookie and handles arrays with missing elements, unlike forEach.
Navigating the sea: Advanced iterations
Sparse arrays and efficiency
Sparse arrays and hardcore optimization call for a traditional for loop with pre-cached length:
Our friend, hasOwnProperty, makes sure you're logging only actual elements.
Plus one for indices
For keeping score value and index, Array#entries is your goal:
Array Looping: Do's and Don'ts
The for...in should steer clear of arrays since it walks over all enumerable properties, not just numeric indices.
Modifying Array.prototype is a big no-no. It can create a disruptive domino effect in iteration behavior.
ES6 compatibility
ES6 features may miss the mark in older environments. Always check your transpiled code or use friendly translators like Babel.
Generator functions
for...of loop and generator functions make a perfect combo for sequences, like Fibonacci numbers:
Pitfall plaza and the map to cross it
Scopes and forEach
The forEach method does not establish its own scope meaning utilized variables are part of the outer scope. When in doubt, use functional expressions within .map() or .filter() for isolated scopes.
The asynchronous affair
Attempting to iterate asynchronously over arrays with forEach can lead to complications. In such situations, go with the for...of with await inside an async function:
Callbacks vs. for...of loop
While forEach saves you from lengthy lines of code, it's quite a diva and does not allow for breaks or continues. The for...of loop, however, is more accommodating.
Was this article helpful?