Iteration

by jeremyjones on March 22, 2011

  • Share
  • CevherShare
  • Share

If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is like the for loop in Perl, Python or PHP but with a little twist. You can use a for loop to repeatedly run a block of script, or once for each member and item of an object. The iterand of the loop is the item index and not the actual item, like this:


for (var myindex in myitems) {

var item = myitems[myindex];
...
}

If you want to loop through Array object, then you should use a traditional for loop like those found in C. As members and items are the same in JavaScript, the for loop will iterate over numeric indexes and named members, but not built-in members like toString or exec.

Some libraries add member functions to the Array prototype. This can make the loop iterate on these member functions as well as the numbers. If you want to avoid iterating member functions in an Array use the following code:


for (var i = 0; i < items.length; i++) {

var item = items[i];
...
}

New libraries and browsers will also provide alternative mechanisms for iteration that are more elegant. The latest versions of Firefox and new libraries like Prototype provide the forEach iteration, which uses and anonymous function. You can use it like this:

items.forEach(function (item) {
...
});

Loops are integral parts of code and it is important to understand how to make them work properly.

Leave a Comment

Previous post:

Next post: