JavaScript While Loop Tutorial

The While Loop In JavaScript

JavaScript includes a while loop to execute code repeatedly till it satisfies a specified condition. Unlike for loop, while loop only requires condition expression.

Syntax:

while(condition expression) { /* code to be executed till the specified condition is true */ }

Example

In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:

while (i < 10) {
    text += “The number is ” + i;
    i++;
}

The Do/While Loop In JavaScript

JavaScript includes another flavor of the while loop, which is a do-while loop. The do-while loop is similar to the while loop the only difference is it evaluates condition expression after the execution of the code block. So do-while loop will execute the code block at least once.

Syntax:do{ //code to be executed }while(condition expression)

Example

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false because the code block is executed before the condition is tested:

do {
    text += “The number is ” + i;
    i++;
}
while (i < 10);

Take Your Free Live Demo Class Now

We Will Call Back You Shortly

Enter Your DETAILS BELOW

We Will Send You the Course Fees Details In Below Number

Enter Your DETAILS BELOW

We Will Call Back You Shortly

Enter Your DETAILS BELOW

We Will Call Back You Shortly

Enter Your DETAILS BELOW

Enter Your DETAILS BELOW TO take

free demo class