1. javascript
  2. /references
  3. /while-loop

The While Loop in JavaScript

Getting Started

The for and while loops are examples of entry-controlled loops. That begs the question; when should you use a for loop instead of a while loop?

Roughly put, we use a for loop when we know the number of times we want to execute the loop body. On the other hand, we utilize a while loop when we want to keep executing the loop body as long as a condition is true.

The while loop has a few nuances that you need to keep in mind. If the condition is initially false, the loop body will never execute. Also, if the condition is always true, you'll end up with an infinite loop, which will crash your program.

The While Loop Syntax

The syntax for a while loop is as follows:

while (condition) {
  // code to execute while the condition is true
}

Inside the brackets, the condition could be numerous expressions that evaluate a boolean value. As long as the condition is true, the code inside the so-called loop body will run. After its execution, the specified condition will be re-evaluated, and if it's still true, the loop body will execute again. Lastly, the process will continue until the condition is false.

While Loop Examples

Counting to Ten with a While Loop

Let's start with a simple example.

let count = 1;
while (count <= 10) {
  console.log(count);
  count++;
}

First off, we declared a variable and initialized it to 1. We then use a while loop to print the value of count and increment it by 1 until it reaches 10, and will only stop executing when our variable holds a value greater than 10.

// Output
1
2
3
4
5
6
7
8
9
10

Using Break to Avoid an Infinite Loop

One of the biggest caveats of the while loop is that if the condition is always true, you'll end up with an infinite loop. Consequently, this can crash our programs, and we'll have to manually stop the execution. To avoid this situation, we can leverage the break statement and exit the loop when a certain condition is met.

Let's see an example:

let i = 0;
while (true) {
  console.log(i);
  i++;
  if (i === 5) {
    break;
  }
}

We start with i as 0 and a condition stated as true inside the brackets. In the loop body, we print the value of i and increment it by 1. We then use an if statement to check if i is equal to 5. If so, break is applied to exit the loop.

The output will be the following:

0
1
2
3
4

Nested While Loop

The while loop can also be nested inside another while loop. Let's see an example where we print a multiplication table using nested while loops.

let i = 1;
while (i <= 10) {
  let j = 1;
  while (j <= 10) {
    console.log(`${i} x ${j} = ${i * j}`);
    j++;
  }
  i++;
}

In this example, we have an outer loop that starts at 1 and goes up to 10. Inside the outer loop, we have another loop that states the same. We print the multiplication table by multiplying i and j, and the loop stops executing when i is greater than 10.

We recommend you try this example in the console to get a feel of how the nested execution works.

Building a Simple Game

For showcase purposes, we'll build a simple game using a while loop. The game is to guess a random number between 1 and 10. We'll keep asking the user to guess until they have the correct number.

const secretNumber = Math.floor(Math.random() * 10) + 1;
let guess = 0;
while (guess !== secretNumber) {
  guess = prompt('Guess a number between 1 and 10');
  if (guess === null) {
    break;
  }
  guess = Number(guess);
  if (guess === secretNumber) {
    console.log('Congratulations! You guessed the number!');
  } else if (guess < secretNumber) {
    console.log('Too low, try again!');
  } else {
    console.log('Too high, try again!');
  }
}

Let's illustrate what we did.

In our simple guessing game, we use the prompt() function to get the user's guess and the Number() function to convert it to a number type. We check if the user has canceled the prompt, and if so, we use the break statement to exit the loop.

If the user's guess is not equal to the secret number, we provide feedback to the user by using an if statement to check whether the guess is too low or too high. We then prompt the user to guess again, and the loop continues until the user guesses correctly.

Once they've guessed correctly, we set the value of the guessedCorrectly variable to true, which terminates the loop. Finally, we provide feedback to the user that they have the right number.

Additional Resources

The for Loop

The for...in Loop

The for...of Loop

The do...while Variation

Break and Continue in JavaScript