Javascript while Loop


The while loop is the simplest loop in JavaScript with the following syntax:

while (expr) {
   statement
}

This syntax means that as long as the expr expression is TRUE, statement is executed until expr is FALSE, and statement represents the action or logic to be executed.

The following example uses the while loop to output 1 to 10:

var i = 1;
while (i <= 10) {
   document.write(i + "<br />");
   i++;
}

operation result:

1
2
3
4
5
6
7
8
9
10

do while loop

The do while loop is very similar to a while loop, except that the do while guarantee must be executed once, while the while may not do anything when the expression does not hold.

do while loop Syntax:

do {
   statement
} while (expr)

example:

var i = 1;
do {
   document.write(i + "<br />");
   i++;
} while (i <= 10);

This example also outputs 1 to 10, but unlike the while loop, the value of i is output at least once, regardless of the initial value of i.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook