749Javascript, Array and For-Loops
Ok, looping over an array is something that we do all the time, for most of us it has become a second nature.
var myArray = ["a", "b", "c", "z"]; for (int i=0; i<myArray.length; i++) { console.log(myArray[i]); }
But I recently came across a Javascript loop that puzzled me slightly.
var myArray = ["a", "b", "c", "z"]; for (var i=0,f ; f=myArray[ i++]; ) { console.log(f); }
Let’s have a closer look what’s happening here. As a reminder, For-statements have the following structure:
for (initiation; condition; increment) { block }
In the initiation, variables are initiated; Condition tests this var, and if it returns true, continues another loop; and here’s something funny; the increment is left blank. Don’t panic, because we are already incrementing i at the condition test.
This is equivalent:
var myArray = ["a", "b", "c", "z"]; for (var i=0,f ; f=myArray[ i]; i++) { console.log(f); }
This, however, is not the same:
var myArray = ["a", "b", "c", "z"]; for (var i=0,f ; f=myArray[ ++i]; ) { console.log(f); }
i gets incremented before it is used to traverse myArray, therefor resulting in this output:
b c z
In nice and simple arrays like in this example, it should not make any difference to test the array length at every time coming around, but a larger ones it might be beneficial.
As usual, take care that the array does not contain any falsy objects. And don’t loop an object that way.
Thanks to the Re-introduction to Javascript https://developer.mozilla.org/en/a_re-introduction_to_javascript for clarifying that issue for me.
Turns out things are not so clear after all. Let’s consider the following case: I have an array of numbers, I’d like to get the sum of all numbers in the array.
One way to do it:
var myArray = [1,2,3,5,7]; for (var i=0, sum=0; i<this.length; i++) { sum += this[i]; } console.log(sum); // 18
So, shouldn’t this work too…?
var myArray = [1,2,3,5,7]; for (var i=0, sum=0; sum = myArray[i]; i++) {}; console.log(sum); // undefined
Apparently not… I am trying to find out why not.
This, on the other hand works:
for (var i=0, sum=0; this[i]; sum+=this[i++]){};