Skip to content

While loop JavaScript | Example code

  • by

A JavaScript while loop executes a block of code until a condition evaluates to true. Where the condition is evaluated before executing the statement.

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

Example While loop JavaScript

Simple example code executes a statement or code block repeatedly as long as an expression is true using JavaScript while loop.

Run the loop until i is less than 5.

<!DOCTYPE html>
<html>
<head>

  <script>
    i = 0;
    while (i < 5) {
      console.log("The number is " + i);
      i++;
    }
  </script>

</head>
<body>

</body>
</html>

Output:

While loop JavaScript

Print Array elements using a while loop. The code in the loop will run, over and over again, as long as a variable (i) is equal to the length of the Array.

  <script>
    const cars = ["BMW", "Volvo", "Saab", "Ford"];
    var l = cars.length;
    var i = 0;

    while (i != l) {
      console.log(cars[i]);
      i++;
    }
  </script>

Output:

Print Array elements using while loop

Do comment if you have any doubts or suggestions on this JS Loop topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *