First of all, when I talk about the standard ”FOR loop”, I mean something like
instead the ”FOR-IN loop” is something like:
The two main problems with for-in loop are : 1) It enumerates through all the properties even the ones associated to the Object (that can be augmented previously) 2) The order of the elements is not guaranteed.
You may not interested in the order of the elements(even if often you are), but you need to deal with the first issue and that’s what can happen:
1 2 3 4 5 6 7 8 9
The correct way to execute that loop is using the for loop:
1 2 3 4 5 6 7 8 9 10
Actually, we can make a micro-optimization to this, “caching” the length of the array and avoiding every time to calculate the length of the array.
1 2 3 4
Notice that there is a comma between “var i=0” and “tot=myArray.length” as the “for loop” accepts three expressions.
If you find this last way a bit weird, you could do something like:
1 2 3 4 5 6
In the next post, I may go through where the “for-in” loop is used.