1. Technology

Learn Modern Unobtrusive JavaScript

Loops

By

For Loops for NodeLists and Arrays

The last tutorial introduced us to a loop that processes all of the elements in a nodelist. The for loop contains three statements separated by semi-colons hat represent the statement to initialise the loop, the condition to terminate the loop, and what to change between iterations through the loop respectively. Exactly the same processing can be used to loop through all of the elements in an ordered array.


for (var i = 0; i < elem.length; i++) {
   // some code here
 };

This is not the most efficient way of coding this where the length of the nodelist or array is not being altered by the content of the loop. The reason for this is that we are performing a lookup of the length each time around the loop in order to determine whether the we have reached the end. There are two different ways that we can make this more efficient depending on whether we specifically need to process the entries in ascending order or whether the order doesn't matter and we can process in reverse order instead.


for (var i = elem.length - 1; i <= 0; i--) {
   // some code here
 };

This version of the loop reverses the order in which we process the entries starting at the end and reading back to the start. This means that we only need to retrieve the length once at the start. It does however mean that the entries get processed in the opposite order to the way that they appear in the array or nodelist. This is not always a desirable option for loop processing.


for (var i = 0, var j = elem.length; i < j; i++) {
   // some code here
 };

This version of the loop combines two statements together in the initialise statement by using a comma separator. Multiple statements can be added into any for loop like this in either the first or third statement or both. Obviously you can't di it with the second statement since that needs to be a condition test. The length of the nodelist or array is assigned once to a simple variable and that variable is tested in the condition each time around the loop instead of the length property.

Hang on a minute though, didn't we decide several tutorials back that variables and properties are the same thing in JavaScript? Well yes they are but there is an efficiency aspect to accessing them depending on how you reference them in your code. For every dot that you include in a method or property reference the actual time that will be taken to access that field will be slightly increased compared to if we have a way of referencing it more directly. This means that by supplying a more direct way to access the length will result in a slight increase in the speed of the loop which may be particularly noticable if the loop contains hundreds or thousands of entries.

For loops like this need not be restricted to processing through arrays or nodelists. They can be used where ever you want to repeat processing of the same statements until a particular condition is met.

For Loops for Objects

Objects cannot be processed using a for statement coded like this since the properties and methods in an object are not ordered and there is no associated length. Instead you can loop through the enumerable properties and methods of an object by using a for statement with a slightly different format.


for (var ent in objname) {
   // some code here
 };

A loop coded like this will loop through all of the enumerable properties and methods of the object objname. Where we had i as a loop counter in the prior type of for loop, with this loop we have ent that represents the current property or method being referenced in a particular iteration of the loop. You can of course specify your own preferred values to use in place of these simply by substituting the field name of your choice.

What is not so obvious when using a loop like this is which of the properties and methods are enumerable. Perhaps the easiest way for you to find out accurately is to actually set up such a loop on existing objects that displays the name of each property and method that it finds. Those will be the ones that are enumerable.

While Loops

For loops are not the only type of loops that exist in javaScript. There are two further types of loop that you can use wher you want to repeat the same process multiple times either while a particular condition is met or intil a particular condition is met. These are done using two variations of a while loop.


while (x == y) {
   // some code here
 };

This loop will test the condition upon entry into the loop and if the condition is true it will process the content of the loop. It will then repeat this process until the condition is false. Where the condition is false when the loop is first tested then the content of the loop will not be run at all.


do {
   // some code here
 } while (x == y);

This variant on the while loop moves the condition test from the start to the end of the loop and so the content of the loop will run at least once regardless of whether the condition is true or not.

Skipping Entries and Early Exit

There may be occasions where you need to check whether some additional conditions are satisfied before processing a particular entry. While this can be done by nesting an if statement within the loop, it can become difficult to read where there is a lot of complex code to contain within the loop. The continue statement provides an easy way for us to tell the loop to skip over the rest of the loop processing for the current entry and to immediately move on to process the next. Similarly the break statement should allow us to prematurely exit from the loop irrespective of whether the termination test for the loop has been satisfied or not.

More of This Tutorial

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. Unobtrusive JavaScript - Loops

©2014 About.com. All rights reserved.