How to Use the While Loop in JavaScript

09/30/2021

Contents

In this article, you will learn how to use the while loop in JavaScript.

Using the while loop in JavaScript

A while loop is a control structure in JavaScript that allows you to repeatedly execute a block of code while a condition is true. The while loop is commonly used when you want to perform a task repeatedly until a specific condition is met.

Syntax

Here is the basic syntax for a while loop:

while (condition) {
  // code to be executed
}

The code inside the loop will continue to execute as long as the condition is true. Once the condition becomes false, the loop will terminate.

Example

Here is an example of a while loop that prints out the numbers from 1 to 5:

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

In this example, the loop will continue to execute as long as the value of i is less than or equal to 5. Inside the loop, the value of i is printed to the console, and then incremented by 1.

Tips for working with while loops

Here are some tips for working with while loops in JavaScript:

  • Be sure to include a statement inside the loop that will eventually cause the condition to become false, otherwise you will end up with an infinite loop that will crash your program.
  • You can use the break statement to exit the loop early if a certain condition is met.
  • You can use the continue statement to skip over certain iterations of the loop if a certain condition is met.