Iteration in Javascript

If you have come to JavaScript from a background in Java or C, you will like the variation on the “for loop“.

It is similar to 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 code 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 an 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 and 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 an 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.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *