More about while loops

You should have seen as many x's as you asked for. Let's go over this:

First, we ask for the number of x's:

var width = prompt("How many x's would you like? (1 - 10 is good)", "5");

Next, declare a few variables:

    var aLine = "";
    var loop = 0;

And now for the important part:

    while (loop < width) {
         aLine +=  "x";
         loop++;
    }

This says, "while the variable loop is less than the requested width of the row of x's, add another x to the line and then add one to the value of loop." This loop will keep adding an x to the line and adding one to the value of loop until loop is no longer less than the requested width. Here's a timeline of what happens when a person chooses two x's at the prompt():

Time 1
Start the process
  • aLine = "" (because we initialized it to be "")
  • loop = 0 (because we initialized it to be 0)
  • width = 2 (because that's what the user asked for)
  • 0 is less than 2 so
  • aLine = aLine + "x", so now aLine = "x"
  • loop = loop + 1, so now loop = 1
 
Time 2
Back into the loop:
  • loop = 1
  • width = 2
  • aLine = "x"
  • 1 is less than 2 so
  • aLine = aLine + "x", so now aLine = "xx"
  • loop = loop + 1, so now loop = 2
 
Time 3
Back into the loop: 
  • loop = 2
  • width = 2
  • aLine = "xx"
  • 2 is NOT less than 2 so
  • fall out of the loop and do what follows

And what follows is:

    alert(aLine);

Throw up an alert box announcing aLine.

This sort of loop is so common that programmers have developed a few shortcuts. Using the shortcuts, the while loop could have been written like this:

    while (loop < width) {
         aLine += "x"; // this was aLine = aLine + "x";
         loop++;   // this was loop = loop + 1;
    }

The first line, aLine += "x", says "add x to myself." This shortcut works with numbers, too. If you have a_number = 5, and you write, a_number += 3, it's just like writing a_number = a_number + 3. Programmers are lazy; they're always coming up with shortcuts like this.

The next line, loop++, means "add one to myself." So, loop++ is the same as loop = loop +1, which could also be written loop += 1. Each of these is equally good. Which one you use depends on how lazy you are.

Just like there's more than one way to add 1 to a number, there's more than one way to write a loop. while loops aren't the only kind of loops out there. Another popular one is the for loop.