JS Loop - While

JavaScript

What is a loop?

A loop is a piece of code that allows us to repeat a code multiple time based on some condition.

Why use loop?

We use loop to avoid retyping a piece of code when we want to repeat it multiple times.

Example: We can use loop and print "Hello World" 10 times using one console.log() or we can write the console.log() 10 times and get the job done.

Though, the first option looks better than the second.

while loop

We use the while keyword to create a while loop.

Syntax

while ( condition ) {
//some code
}

If the condition of the while loop is satisfied then the body of the while loop is executed otherwise, skipped.

In the following example we have a while loop that helps in printing out "Hello World" 10 times in the browser console.

var i = 1;
while ( i <= 10) {
console.log("Hello World");
i++;
}

Explanation

In the above code we have a variable i which is set to 1. Then we check if i <= 10. If this is true then we enter into the while loop. Inside the loop we print the "Hello World" message in the browser console. Next we increment the value of variable i by 1 using the increment operator.

This process is repeated as long as i <= 10. When the value of i becomes 11, we exit the while loop.

Another type of while loop is the do-while loop.

do while loop

We use the do and while keyword to create a do-while loop.

Syntax

do {
//some code
} while ( condition );

If the condition of the do-while loop is satisfied then the body of the do-while loop is executed otherwise, skipped.

The difference between a while and a do-while loop is:

In a while loop we first check the condition and then execute the loop body.

In a do-while loop we first execute the loop body and then check the condition at the end.

Note! In a do-while loop the body will be executed at least once.

In the following example we have a do-while loop that will print "Hello World" 10 times.