Explain Codes LogoExplain Codes Logo

Loop (for each) over an array in JavaScript

javascript
for-of
async-await
array-methods
Nikita BarsukovbyNikita Barsukov·Aug 19, 2024
TLDR

To iterate through an array simply using forEach:

[1, 2, 3].forEach(item => console.log(item));

Dive deeper for optimal tips and tricks, handling complex scenarios, performance considerations, and control flow that JavaScript offers.

Choose Your Iteration Weapon

Simple and clear with for-of

To iterate over array elements in an elegant way without any fuss about the index, the modern for-of loop is your friend:

for (const item of [1, 2, 3]) { console.log(item); // item, this print's for you! }

Precision control with for loop

for loop is your Swiss army knife. If your logic demands granular control over the iteration, this classic is the way to go:

for (let i = 0; i < array.length; i++) { // Insert "I control the Iteration" joke here 😉 }

Quick transformation with spread syntax and Array.from

Need to turn iterables or array-like objects into a true array fast? Spread syntax lets you rest:

const set = new Set([1, 2, 3]); const array = [...set]; // [1, 2, 3]

It's not the only hero in town, though. Array.from performs transformations too, and can map elements for you:

const array = Array.from(set, value => value * 2); // [2, 4, 6]

Demystifying async with loops

Taking on async/await? Use for-of or traditional for loops, and you can confidently wait for asynchronous operations:

for (const item of asyncArray) { await process(item); // Hold on, let me finish this first! 🕒 }

Making array-like objects play nice

Dealing with NodeLists, HTMLCollections, or arguments? Array.from or Array.prototype.slice.call are your compatibility adapters:

const arrayLike = document.getElementsByTagName('div'); const array = Array.from(arrayLike); // Now you're speaking my language

Coding cleanly with array methods

Enhance readability and follow the functional programming style with map, filter, and reduce. But if you're not keeping the returned array, favor forEach or a loop. Remember, with great power comes great responsibility of proper tool selection!

Refining your iteration skills

Performance wise iterations

While higher-order functions like forEach, map, filter and others add style and readability, you might get a speed boost with a good old for loop, especially when handling large arrays.

Secured property iteration

Iterating over an object's properties with for-in? Stay safe from inherited properties by using Object.hasOwn or Object.prototype.hasOwnProperty.call:

for (const key in object) { if (Object.hasOwn(object, key)) { // Property checked, all clear to proceed! 🚓 console.log(key, object[key]); } }

Smart scoping in async loops

When you're within async functions inside loops, use let to declare loop variables. It ensures the correct scope, dodging potentially pesky closure issues:

for (let i = 0; i < asyncArray.length; i++) { await process(asyncArray[i]); // Now now, wait your turn! 🔄 }