JavaScript

JavaScript While Loop – Explained

In computer programming, loops are used to iterate (repeatedly execute) through a block of code until a specific condition is fulfilled. Most major programming languages include multiple types of loops, for example, for and the while loop. These loops are syntactically different but are essentially used for the same purposes meaning they can be replaced with each other in most cases. This write-up will be focussing on the while loop:

How to use while loops in JavaScript

We will first discuss the syntax of while loop in Javascript:

while (condition) {
  // Statement
}

The while loop statement takes a single argument which is the condition for the termination of the loop. The loop will keep on iterating until this condition becomes false. Now we will discuss a few examples to better understand while loops.

Note: The browser console is used for the demonstration of examples in this article.

For our first example we’ll look at a program which prints the table of a number to the console. If we do not use any loops then the program will look like this:

console.log("2 * 1 = " + 2 * 1);
console.log("2 * 2 = " + 2 * 2);
console.log("2 * 3 = " + 2 * 3);
console.log("2 * 4 = " + 2 * 4);
console.log("2 * 5 = " + 2 * 5);
console.log("2 * 6 = " + 2 * 6);
console.log("2 * 7 = " + 2 * 7);
console.log("2 * 8 = " + 2 * 8);
console.log("2 * 9 = " + 2 * 9);
console.log("2 * 10 = " + 2 * 10);

The code in the above example looks repetitive; we can perform the same task in a few lines of code using a loop; Here we will use the while loop:

i = 1;
while (i<=10) {
    console.log("2 * " + i + " = " + 2 * i)
    i++;
}

As already mentioned above loops are interchangeable; they can be replaced with each other. The task performed in the example given above can be performed by using a for loop.

In general for loops are used when the loop has to run for a definite number of times whereas the while loop is used when the loop is going to run for an indefinite number of times until the condition is satisfied.

For our next example we will create a program with a while loop which will run for an indefinite number of times:

randomNumber = 0;
while (randomNumber < 500) {
    randomNumber = Math.trunc(Math.random()*1000);
    console.log(randomNumber);
}

In the example given above we first created a variable named randomNumber and assigned it a value 0. This was only done because the while loops check the condition before every iteration (on the first iteration the loop ran because the condition was true as 0 < 500). We then declared a while loop and gave it a condition which is randomNumber < 500. Inside the body of the loop we used the Math object to get a random number between 0 and 999 and assigned this number to the randomNumber variable. Then we used the console.log method to print the randomNumber onto the console.

The while loop kept iterating and the Math object kept generating random numbers until the condition was met which was a random number greater than 500.

How to use break statement with while loop in JavaScript

JavaScript gives us the option to use break statements inside the body of the while loops to terminate the loop. The break statements can be combined with other statements such as the conditional if statements to terminate the loop from inside its body once a specific condition is met.

For our next example we will take the code from our first example and modify it so the loop breaks if there is a multiple of ten inside the table of 2.

i = 1;
while (i<=10) {
    if ((2 * i) % 10 == 0) {
        break;
    }
    console.log("2 * " + i + " = " + 2 * i)
    i++;
}

As 10 satisfies the condition of our break statement the loop is executed after the fourth iteration.

How to use continue statement with while loop in JavaScript

The continue statement skips the current iteration of the loop upon satisfying the condition and moves to the next instead of terminating the loop:

i = 1;
while (i<=10) {
    if ((2 * i) % 10 == 0) {
        i++;
        continue;
    }
    console.log("2 * " + i + " = " + 2 * i)
    i++;
}

If there is a multiple of 10 in the table of 2 then the continue statement skips the iteration and moves to the next:

What is do while loop in JavaScript

The do while loop is built on top of the while loop meaning it is an extension of the while loop.

The while loop checks the condition before execution of the loop’s body. The do while loop evaluates the condition after the execution of the loop’s body.

So the code written inside the do section will always run at least once:

var number = 10;

do {
    console.log("The do while loop is running");
} while (number < 5);

In the example above the code in the body of the do while loop was executed for the first iteration even though the condition was false.

Conclusion

Loops are one of the most powerful tools in any programming language used to iterate over blocks of code. In this article we have learned about the while loop which is a type of loop present in JavaScript and many other programming languages; moreover we also learned to combine the while loop with some other statements to make it more powerful.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.