Loop (for each) over an array in JavaScript
To iterate through an array simply using forEach
:
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:
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:
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:
It's not the only hero in town, though. Array.from
performs transformations too, and can map elements for you:
Demystifying async with loops
Taking on async/await
? Use for-of
or traditional for
loops, and you can confidently wait for asynchronous operations:
Making array-like objects play nice
Dealing with NodeLists, HTMLCollections, or arguments? Array.from
or Array.prototype.slice.call
are your compatibility adapters:
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
:
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:
Was this article helpful?