WDI Fundamentals

WDI Fundamentals Unit 9


We've covered how we can tell our programs to make decisions. Now, let's look at how we can tell them to take repeated/ongoing actions.

The while Loop

To tell your program to repeat something, you use a tool called a loop — once your program has finished running a block of code, it "loops" back to the beginning and starts again.

Suppose that we were to take our if statement from the previous lesson and loop it back on itself. Here's the flow diagram for the if, in case you've forgotten.

Flow Chart for `If` Statement

We're going to make one small (but very important) change to this — instead of advancing to the next bit of code after executing the block, we will loop back to our condition.

Flow Chart `If` -> `While`

Now, we have a loop. So long as our condition remains true (or at least "truthy"), we will continue to run that block of code over and over again. This type of loop is called a while loop and can be found in nearly every programming language. Here's the general rule for writing while loops in JavaScript:

while (someCondition) {
  // A block of code.
}

As you can see, it is written in almost the exact same way as an if statement.

Test Yourself

  • Consider the following code:
var x = 10;
while (x > 5) {
  x -= 2;
}

How many times will this loop run? What will the final value of x be when it is finished?

  • Here's another loop. This loop uses y++, which is a more common way of writing y += 1.
var x = 10;
var y = 1;
while (x < 20) {
  y++;
}

How many times will this loop run? What happens when you try to run this code?

A while loop can run indefinitely as long as your condition remains true. This is usually a bad thing, so, when using a while loop, it's very important to plan out beforehand how you will "escape" the loop by making your condition evaluate to false.

Consider the following example:

var z = 0;
var myString = '';
while (z < 5) {
  myString += 'X';
  z++;
}

Q: How many times does this loop run? What's the final value of myString?

A: Each time this loop runs, the value of z increases by 1. Because its initial value is 0 and the condition becomes false the moment that z becomes 5, our loop will run exactly 5 times. As a result, the string myString has a final value of "XXXXX" (5 Xs).

Confused? Here's the play-by-play:

  • z is set to 0 and myString is set to "".
  • z is 0, therefore z < 5 is true and the block gets executed.
    • (In the block) "X" gets added to the end of myString; it is now "X."
    • (In the block) z is increased by 1; it is now 1. Now that the block is done, we go back to the condition.
  • z is 1, therefore z < 5 is true and the block gets executed.
    • (In the block) "X" gets added to the end of myString; it is now "XX."
    • (In the block) z is increased by 1; it is now 2. Now that the block is done, we go back to the condition.
  • z is 2, therefore z < 5 is true and the block gets executed.
    • (In the block) "X" gets added to the end of myString; it is now "XXX."
    • (In the block) z is increased by 1; it is now 3. Now that the block is done, we go back to the condition.
  • z is 3, therefore z < 5 is true and the block gets executed.
    • (In the block) "X" gets added to the end of myString; it is now "XXXX."
    • (In the block) z is increased by 1; it is now 4. Now that the block is done, we go back to the condition.
  • z is 4, therefore z < 5 is true and the block gets executed.
    • (In the block) "X" gets added to the end of myString; it is now "XXXXX."
    • (In the block) z is increased by 1; it is now 5. Now that the block is done, we go back to the condition.
  • z is now 5, therefore z < 5 is now false (because 5 is not less than 5). The block does not get executed again.
  • And, we're done!

What's most interesting about this kind of set up is that, if we changed that condition from z < 5 to z < 10 or z < 100, the loop would change to run exactly 10 or exactly 100 times, respectively. In effect, we have changed the while loop so that it always runs for a fixed, controllable number of times — it will never get stuck in an infinite loop.

This kind of set up is so useful, and is used so frequently, that most languages include a special kind of loop for just this kind of behavior, known as a for loop.

The for Loop

Let's make a few modifications to our while loop.

Flow Chart for `For` Loop

As you can see, there are a couple of key ingredients that make our for loop work. We need: 1) An initialization, which sets up a starting situation (e.g., var x = 0). 2) A condition, which gets evaluated each time we're about to execute the block (e.g., x < 10). 3) A finalExpression, which gets evaluated immediately after the block executes but before the condition is evaluated again (e.g., x++;).

The general syntax for a for loop is:

for (initialization; condition; finalExpression) {
  // A block of code.
}

Test Yourself

var x = 10;
for (var i = 0; i < x; i++) {
  console.log('HELLO'); // This is a command to our console, telling it to display the text `'HELLO'` and advance to a new line.
}
  • How many times will 'HELLO' be printed out in the console?
  • What if we changed the starting value of i to 1 instead of 0 (and all else is the same)? How many times would 'HELLO' get printed to the console?
  • What if we changed the condition from i < x to i <= x (and all else is the same)?
  • What if we changed the final condition from i++ to i += 2 (and all else is the same)? Check your answers in JS Bin.

Feeling good about loops? Let's do another exercise.