JavaScript – While Loop

The while Loop

While writing a program, when we encounter a situation where we need to perform repetitive action, in that we would need to write loop statements to reduce the number of code lines.

JavaScript includes while loop to execute code repeatedly till it satisfies the given condition.

Flow Chart
WHILE-LOOP
Syntax

while (condition expression){
Statement(s) to be executed if expression is true
}

Example:

<html>
<body>
<script>
var count = 0;
document.write(“Starting Loop<br/>”);
while (count < 10){
document.write(“Count : ” + count + “<br/>”);
count++;
}
document.write(“Loop Stopped”);
</script>
</body>
</html>


Output:
While Loop


The do-while Loop

The do-while loop is similar to the while loop except the condition check happens at the end of the loop, means that the loop will always be executed at least once, even if the condition is false.

Flow Chart
WHILE-LOOP
Syntax

do {
Statement(s) to be executed at least once, even if condition is false.
} while (condition expression);

Example:

<html>
<body>
<script>
var count = 10;
document.write(“Starting Loop<br/>”);
do {
document.write(“Count : ” + count + “<br/>”);
count++;
} while (count < 10);
document.write(“Loop Stopped”);
</script>
</body>
</html>


Output:
While Loop

Leave a Reply