I have stumbled into several methods of looping in JavaScript, what I like the most is:
for(var i = 0; i < a.length; i++){ var element = a[i]; }
But as tested here (http://www.robertnyman.com/2008/04/11/javascript-loop-performance/), it should probably be written so that the length is only calculated once.
In jQuery there is a .each that you can stick a function. I like this a little better, because I don't have to type the array twice, like in the above solution.
If JavaScript supported macros it would be a piece of cake to roll your own, but sadly it does not.
So what do you guys use?
forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm. Unlike in AssemblyScript, micro-optimizations of the for loop don't make sense for arrays in JavaScript.
for/in - loops through the properties of an object. for/of - loops through the values of an iterable object. while - loops through a block of code while a specified condition is true. do/while - also loops through a block of code while a specified condition is true.
In theory the while loop is quicker because the for loop looks up the length attribute of foo every time though the loop, but in real-world use it's going to make an immeasurably small difference.
I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:
function createIterator(x) { var i = 0; return function(){ return x[i++]; }; }
Then to use:
var iterator=createIterator(['a','b','c','d','e','f','g']); iterator();
returns "a";
iterator();
returns "b";
and so on.
To iterate the whole list and display each item:
var current; while(current=iterator()) { console.log(current); }
Be aware that the above is only acceptable for iterating a list that contains "non-falsy" values. If this array contained any of:
the previous loop would stop at that item, not always what you want/expect.
To avoid this use:
var current; while((current=iterator())!==undefined) { console.log(current); }
Small improvement to the original, to only calculate the array size once:
for(var i = 0, len = a.length; i < len; i++){ var element = a[i]; }
Also, I see a lot of for..in loops. Though keep in mind that it's not technically kosher, and will cause problems with Prototype specifically:
for (i in a) { var element = a[i]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With