While Loops

While loops execute a code block until the given boolean condition evaluates to false. In other words, while loops continue executing while (or "as long as") the boolean condition evaluates to true.

Here is an example of a while loop:

var counter = 0;
while (counter < 2) {
  console.log("The counter is " + counter);
  counter = counter + 1;
}

This loop prints the following strings to the console:

The counter is 0
The counter is 1

Let's walk through every step of this loop:

var counter = 0; // counter is assigned to 0

// first loop
counter < 2; // true, so the body of the loop is executed
console.log("The counter is " + counter); // prints "The counter is 0" to the console
counter = counter + 1; // counter is reassigned to 1

// second loop
counter < 2; // true because counter is assigned to 1
console.log("The counter is " + counter); // prints "The counter is 1" to the console
counter = counter + 1; // counter is reassigned to 2

// third loop
counter < 2; // false because counter is assigned to 2
// since the boolean condition is false, the loop body isn't executed again

Here is another example that is very similar.

var i = 5;
while (i < 8) {
  console.log("The variable i is " + i);
  i++; // shorthand notation for i = i + 1
}

This code prints the following strings to the console:

The variable i is 5
The variable i is 6
The variable i is 7

The counter variable in loops is often i. In loops, the i++ shorthand notation is frequently used to increment the variable by 1. Recall from Chapter 2.4 that i++ and i = i + 1 are equivalent statements:

var x = 0;
x++;
console.log(x); // 1

var y = 0;
y = y + 1;
console.log(y); // 1
Question Click to View Answer

What does the following code print to the console?

var counter = 25;
while (counter < 28) {
  console.log("The counter is " + counter);
  counter = counter + 1;
}
The counter is 25
The counter is 26
The counter is 27

What does the following code print to the console?

var i = 0;
while (i < 3) {
  i++;
  console.log("I like " + i);
}
I like 1
I like 2
I like 3

The variable i is incremented before the console.log statement, so the results are slightly different from what we've seen so far.

var sum = 0;
counter = 0;
while (counter < 5) {
  sum = sum + counter;
  counter = counter + 1;
}
console.log(sum);

This loops adds the numbers 0, 1, 2, 3, and 4, and assigned the result (10) to the sum variable. This example is a bit more complex because two variables are being reassigned for each loop iteration.

var sum = 0;
counter = 0;
while (counter < 5) {
  sum = sum + counter;
  counter = counter + 1;
}
console.log(sum);

10

This loops adds the numbers 0, 1, 2, 3, and 4, and assigned the result (10) to the sum variable. This example is a bit more complex because two variables are being reassigned for each loop iteration.

<-- Previous (Introduction to Arrays) Next (Infinite Loops) -->