HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

4) Conditionals, Loops and Functions Lesson

Understanding the JavaScript While Loop

8 min to complete · By Ian Currie

One way of performing iteration is with the while loop.

Just like the for loop, the while loop also has a condition. While the condition is true, it runs. Yet it doesn't have any iterator variable like a for loop. This makes it especially prone to infinite loops, something best avoided, unless you are trying to crash the machine!

How Are While Loops Executed

In order to understand the logic behind while loops, here you have an example of an annoying while loop.

Example of a While Loop

let name = "";

while (name !== "your name") {
  name = prompt("Please type your name.");
}

alert("Thank you!");

The code above is a small example program that will keep asking you to type, literally, your name. Not your actual name, but the characters, y o u r n a m e and will keep asking for that input, annoyingly. Copy and paste the following code into your browser console to see it in action:

Understand the Inner Workings of a While Loop

Using the example provided above, let's try to understand the different elements of a while loop.

First, the name variable is set to an empty string. This is so that the name !== 'your name' condition will evaluate to true and the program execution will enter the while loop’s clause.

The code inside this clause asks the user to type "your name", which is assigned to the name variable. Since this is the last line of the block, the execution moves back to the start of the while loop and re-evaluates the condition(name !== 'your name'). If the value in name is not equal to the string 'your name', then the condition is true, and the execution enters the while clause again.

When Will the Iteration Stop

Obviously most people will initially type their actual name, and so the program will keep on asking the same question! But once the user types the string your name, the conditional statement of the while loop will be 'your name' != 'your name', which evaluates to false and breaks out of the while loop. JavaScript then skips past the while loop and continues running the rest of the program.

Choosing the Right Loop: For Vs While

Take a look at this example:

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

Notice anything about this loop? Its very similar to the first example in the lesson about for loops. That is right, for and while loops are actually mostly interchangeable! See this StackOverflow thread for a discussion on that.

For most use cases its just a nicer and more elegant way to write that type of loop, though if you never want to use a while loop and prefer to do everything with for, you could probably get away with it. Until your new client or boss wants the code to be more concise that is!

Try and write for loops and then transforming them into while loops.

The break and continue keywords

Like forloops, while loops can also make use of the break and continue keywords to control the iteration.

Here's a short example of these keywords in a while loop:

let i = 0;
while (i < 10) {
  i++;
  if (i === 3) {
    continue; // Skip the rest of the loop when i is 3
  }
  if (i === 6) {
    break; // Exit the loop when i is 6
  }
  console.log(i);
}

In this snippet, when i is equal to 3, the continue keyword skips the console.log statement, so the number 3 is not printed. When i reaches 6, the break keyword halts the loop entirely, so the numbers 6 through 10 are not printed.

The control that break and continue offer within while loops is essential for precise loop management. Continue is particularly useful for bypassing an iteration when certain conditions are met without exiting the loop. This avoids executing subsequent code and effectively starts the next iteration. Meanwhile, break offers a straightforward way to exit the loop from any point within its body, which is useful when a terminating condition is met, or if continuing the loop is unnecessary or could result in an error. These keywords help maintain readable and efficient code, especially in loops where the number of iterations is not fixed and depends on dynamic conditions.

Illustration of a lighthouse

Just like the for loop, the while loop also has a condition. While the condition is true, it runs. Unlike a for loop, it does not explicitly define the initialization, condition, and increment/decrement in a single line, so care must be taken to ensure that the loop has the proper logic to terminate, otherwise it may lead to an infinite loop which can crash the program.

Summary: What Is the Javascript While Loop

  • The while loop is very similar to the for loop
  • The code gets executed while a condition is true
  • The code will stop when the condition is false
  • while loops and for loops mostly interchangeable
  • The break keyword allows you to break the code in the middle of its execution