Great note on the
while loop, it’s generally my go-to method of looping through
NodeList and other arrays. In very rare cases do I ever use
for loops, mainly because there are few instances where I need to loop through an array from it’s front-most item.
Here is a great jsPerf for iterative performance.
For in loops don’t seem to be very reliable for large arrays.
while loops generally take the cake in terms of performance, and is why I use them whenever I can.
The reason why is likely due to the fact that it’s only performing a single check while iterating, while the
for loop is adding a very minimal extra to it’s overhead. For the small loops it’s negligible, but for larger sets of items it can make an noticeable effects.
As for what you’re saying: yes, using
let inside the declarative portion of the loop is fine. This is because just like in C, the variable is initialized before the loop starts.
My through comes into
let specially inside of the code block. Since it only exists inside of the scope at the time of the loop, there is a chance that the JS engine might misinterpret the
let directive as ‘Hey, the code wants to check this location in memory, I’m going to check if it’s been properly initialized first before setting it’s value.’
Ths is especially true in the case of
let inside of code blocks, because by nature it will destroy itself once that block of code has fished executing.
That’s the issue I’m trying to address with this example. It’s very niche, but for large scaling loops (for large data-sets containing thousands or more items). For some of the Node projects I work on these are the sorts of things I’m forced to take into account, since sometimes I’m processing arrays with hundreds of thousands of items. It’s in these cases I strictly follow what I’ve shown.
But yeah, for smaller loops it’s not really a huge issue. I’m just personally obsessed with operation-per-second performance.