Looping Over Arrays
Looping over arrays is one of the most common tasks in JavaScript, and there are dozens of ways to do it. In my code, I stick to just two versions for readability and performance reasons.
Both versions use the for statement. The simpler of the two should look familiar from Chapter 1, as shown here:
var myArray = [1, 2, 3, 4, 5]; for (var i = 0, l = myArray.length; i < l; i++) { console.log(myArray[i]); }
The one important difference is in the setup expression, where I declare both i and l at the same time. I do this because the test is executed every time the loop runs, and I can save a few milliseconds by saving the value of length to a variable from the start.
My second favorite loop pattern can be used only if every element in the array is "truthy" (not zero, false, an empty string, null, or undefined), so I use it only in special cases. The most common case is when I'm looping over elements in a page.
// Get a collection of <a> tags from the page // and loop over them var allLinks = document.getElementsByTagName("a"); for (var i = -1, link; link = allLinks[++i];) { console.log(link); }
The previous is still a normal for loop, but I'm doing some tricky things in each expression:
- In the setup, I declare i as –1 and link as undefined (it doesn't need a value yet).
-
In the test, I access the next link in the allLinks collection by incrementing i and using the bracket operators ([]). The first time this happens, -1 becomes 0 and returns the first item in allLinks. I then assign that value to link.
Note that I use the increment (++) operator on the left side of i so that I add 1 to i before evaluating it in the brackets.
- In the increment expression, I don't do anything because I already incremented i in the test. Note that the semicolon is still required after the test.
I like this usage of the for loop because I don't need to worry about i in the body of the loop. I have the link variable to work with as soon as possible. It's also a great demonstration of the flexibility of JavaScript.
forEach(loopFunc)
Looping over arrays using functions is increasingly common, especially in certain libraries. Modern browsers support the forEach() method, but you can also build your own.
function arrayForEach(array, loopFunc) { // If the browser support forEach, use it because // it will be faster if ("forEach" in array) { return array.forEach(loopFunc); // Otherwise, loop over the array and pass in // the array values to the loop function } else { for (var i = 0, l = array.length; i < l; i++) { loopFunc(array[i], i, array); } return array; } } function doSomeMath(num) { console.log(num * 10 - 5); } arrayForEach([1,2,3], doSomeMath);5
15
25