While Loops

Open the project folder

In our starter files, open the index.html page from this lessons folder:

06.Loops-and-conditionals > 03.While-loops

The while loop structure

The while loop can look a little simpler than a for loop. And the basic setup looks again like many other things in JavaScript, such as a basic function, an if statement, and even the for loop:

while () {

}

A while loop will continue to run as long as a condition is true. Looking at the following code, we have a simple number variable, and then the loop will keep running while the number is less than 30:

let number = 0;
while (number < 30) {

}

This check is performed before the code in the loop is ran, so if it is false, the loop will stop. As with the for loop, we also need a way to stop so it does not turn into an infinite loop. And we do this inside the loop by incrementing the value of number by one each time, meaning this will run 30 times before it stops:

let number = 0;
while (number < 30) {
  // do something
  number++
}

Example

Let’s give this a try in the starter files. This example will have two variables, and we can simulate only letting people into a stadium if the capacity is not yet reached. Add the following code between the script tags:

const stadiumCapacity = 100;
let currentlyEntered = 0;

while (currentlyEntered < stadiumCapacity) {
  console.log('enter');
  currentlyEntered++;
}

This will log the text of enter 100 times in the console. Meaning the loop stops running when the stadium capacity has been reached.

The do…while loop

A variant of this is the do…while loop, and this is like a switched around version of the while loop.

Remember, the code in the while loop runs after the condition is checked, we can switch this and make sure the code runs first, then perform the check. This is useful if we always want to make sure the code runs at least once before the loop is stopped.

This is how it looks:

do {
  console.log('enter');
  currentlyEntered++;
} while (currentlyEntered < stadiumCapacity);

Notice the code to run is in the first block, before the run condition is even checked. We can test this will always run once by setting both variables to be 100:

const stadiumCapacity = 100;
let currentlyEntered = 100;

And this will still run once even though the capacity is full. These is just an alternative depending on if we want the code to run first, or, test against the condition first.