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>

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




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.

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

    while (i != l) {


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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading