The typical format for a ‘for loop’ to run through the list items in an array is as follows…
var myArray = [1, 2, 3, 5, 8, 13, 21, 34]; for (var i = 0; i < myArray.length; i++) { //myArray[i] becomes the variable run inside the loop }
But you’ll notice that every time the loop is run, the length of the array is calculated…. Yet the number is always going to be the same… So we’re just wasting time processing for no reason… We could create a variable outside the ‘for loop’ and use that…. Or declare it when we set the loop up…. Like this:
for (var i = 0, ii = myArray.length; i < ii; i++) { //myArray[i] becomes the variable run inside the loop }
This time, before the first semi-colon, we can declare more variables and spped the script up, whilst keeping it nice and neat at the same time…
Another little gem from Kevin Yank at Sitepoint
Main Category