WEB150 » Lecture 04: Loops

Update: June 17th, 2010

Assignment - Loops

You will need:

  • Conditional Equal Statement: if (x===y) { }
  • Conditional Less Than Statement: if (x < y) { }
  • Conditional Greater Than Statement: if (x > y) { }
  • The Standard For Loop (in today's lesson)
  • console.log()
  • Array.length
  • The following JavaScript code snippet:
// define two sets
var setA = [1,2,3,6,7];
var setB = [5,4,3,2,1];
 
// loop through them to find where they intersect
// (this is where you will create the for loops)

The Task:

Compare the values in setA against the values of setB.

For each value in setA, log to the console either true or false to tell if the item is LESS than each item in setB.

If the item in setA is equal to the item in setB, write to the console that you are skipping that item: console.log('skipping equal item') and "continue" the loop to the next item.

If the item in setA is greater than an item in setB, 'break' the loop.

Hint

Loop through setA. Within that loop, loop through setB. All of your code will be within that second loop :)

Example Output

1 is less than 5
1 is less than 4
1 is less than 3
1 is less than 2
skipping equal item
2 is less than 5
2 is less than 4
2 is less than 3
skipping equal item
3 is less than 5
3 is less than 4
skipping equal item

Lecture Notes

Loops

This is a universal programming construct. There are many situations where you need to go through a list and perform an action for each item or just generally run code over and over a certain number of times. This is handled by setting up a loop construct, which evaluates a conditional statement for boolean true/false, running a statement (or block of code) contained within the loop if the condition is true. Each time the loop is executed is called an iteration.

There are four ways of performing loops in JavaScript:

The "While Loop": while( condition expression ) statement

This is the simplest type of loop, but not the most commonly used. In fact, you may not use it at all--but it's a good place to start in understanding how loops work.

The execution of the while statement begins with the evaluation of the condition expression. If that expression evaluates to false from the start, the statement will never be executed. If that expression evaluates to true from the start, the statement will be executed. And as long as that expression evaluates to true, the statement will be executed. But once that expression evaluates to false, the program's flow of execution moves on to the next statement, if any. Look at this example:

var count = 0;
while( count < 10 )
{
   console.log( count );
   count++;
}

The "Do / While Loop": do statement while( condition expression )

The do / while loop is even less common than the while loop. But it's the next step in the loop logical progression.

The execution of the do / while statement begins with the execution of the statement. Once the execution of the statement is done, the evaluation of the condition expression in the while clause takes place. If that expression evaluates to false from the start, the program's flow of execution moves on to the next statement, if any. If that expression evaluates to true, the statement will be executed again. And as long as that expression evaluates to true, the statement will be executed. But once that expression evaluates to false, the program's flow of execution moves on. What make this construct unique is that the statement within the construct is executed at least once; The following example should produce the same results as with the while statement above:

var count = 0;
do
{
   console.log( count );
   count++;
} while( count < 10 );

The Standard "For Loop": for( initialize; condition; increment ) statement

This is the most common kind of loop you will use--since most of your actions will usually be on arrays of data.

The execution of the for statement begins with the establishing a counter, how the counter is incremented, and evaluating a test expression - very much like the condition expression of the while and do / while constructs. Once this initialization and evaluation is done and yields a result of true, the statement is executed. If that expression evaluates to false from the start, the statement never executes. As long as that expression evaluates to true, the statement will be executed. But once that expression evaluates to false, the program's flow of execution moves on. The following example should produce the same results as with the while and do / while statements above:

for( var i = 0; i < 10; i++ )
{
   console.log( i );
}

The Object "For in Loop": for( variable in object ) statement

The execution of this for statement begins with a list of properties from an object. Once a property is stored in the variable, the statement is executed. If there are no properties (highly unlikely for objects intrinsic to the language), the statement never executes. As long as a property is stored in the variable, the statement will be executed. But once there are no more properties in the object, the program's flow of execution moves on. The following example displays all the property names and values of the document object:

var obj = {
   "count":1,
   "clean":true,
   "name": "My Object"
};
for(var p in obj){
   console.log( obj[p] );
}

Nesting Loops

It's fairly common that you will want to loop through 2 sets of information to compare items or filter 1 set based on another--or sometimes you just need to run code on a set of data for each item in another set.

Loops can be easily nested, but make sure you watch out for your variable names. The standard is to start your first level of looping using "i" as your iteration counter. Then proceed alphabetically. So a second level loop would use "j" as the iteration counter and a loop within that would use "k", then "l" and so on.

Warning: If you find that you are looping more than 3 levels deep, there's a very, very good chance that there's a better way to do whatever it is you are trying to do.

Here, we loop through suits and ranks to generate a new array, filled with a full deck of cards:

var ranks = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"];
var suits = [
   "S", // spade
   "H", // heart
   "C", // club
   "D" // diamond
];
var cards = [];
for( var i = 0; i < suits.length; i++ ) {
    for( var j = 0; j < ranks.length; j++ ) {
       console.log(ranks[ j ]+suits[ i ]);
       cards[ cards.length ] = ranks[ j ]+suits[ i ];
    }
}

Break and Continue

There are two ways that the normal execution of a repetition construct can be modified. You can either break the operation--meaning, you stop it completely, regardless of how far along it's gone. Or you can continue to the next iteration, ignoring all remaining code within the scope of the loop.

Break Example

for( var i = 0; i < 10; i++ ) {
      console.log('start of iteration '+i);
      if(i===4){
         console.log('found what we want, no need to keep looping');
         break; // kill the loop immediately
      }
      console.log('end of iteration '+i);
}

Break Example

var obj = {
   "count":1,
   "clean":true,
   "item":2,
   "name": "My Object"
};
for(var p in obj){
   if(p==='clean' || p==='item'){
      console.log('found one of the things I was looking for: '+p+' = '+obj[p]);
      // continue immediately to the next item 
      // skipping the remaining code
      continue;
   }
   console.log( 'found an item indexed by the name '+ p +' with a value of '+obj[p] );
}
No comments yet.
You must be logged in to post a comment.
TOP