DEV Community

Cover image for Possible ways of Iterating ARRAYS in JavaScript

Possible ways of Iterating ARRAYS in JavaScript

Aashritha Shiva on May 29, 2020

Arrays are used to solve most of the coding problems. So when starting with this, there raises a question for everyone i.e “What are the possible w...
Collapse
 
miketalbot profile image
Mike Talbot ⭐

Thanks for the article - it certainly does cover off all of the methods.

I'm just about to write on this subject myself - and having just been researching:

  • Firstly your first examples don't seem to line up e.g. (1) says its a for(;;) loop, but your example isn't - it's some kind of filter. There are a couple of others that are also not what the title says.

  • Secondly for(;;) loops are held to be fastest - and jsPerf and jsBench.me will tell you that. But run it in your own browser or codesandbox and you may be in for a surprise.

  • Thirdly - reading the length every iteration doesn't appear to make any difference, in fact it can be faster because modern browser Javascript engines optimise for it. They know that JS is single threaded and spot the pattern.

Collapse
 
aashrithashiva29 profile image
Aashritha Shiva • Edited
  • I haven't checked the example issue... I have corrected it. Thanks for this :)
  • yeah, I have come to the conclusion after performing the test with performance.now(). But it was wrong. Yes "for loop is the fastest"
  • and caching length inside the loop is fine!!
  • jsPerf was great And to correct "for..of" is faster compared to for..in and forEach but indeed for is the fastest one over all others. Thanks for listing out these points.
Collapse
 
iainfreestone profile image
Iain Freestone

Your third point is interesting I had wondered about this in the past. Off to look further into this!

Collapse
 
apooja1029 profile image
apooja1029

All the 8 ways given above to Iterating arrays in javascript are fabulous. Thanks for shring such a good information, it helped me a lot.
lettertemplate.org/
manifestationlawofattraction.com/
bestwishesmessages.com/

Collapse
 
aashrithashiva29 profile image
Aashritha Shiva

Thank you for reading. Please refer it out.