Looping Statements in JavaScript

In this tutorial, we will learn about Looping Statements in JavaScript We use Looping Statement to run a piece of code multiple time without writing it again and again. Suppose we want to write 1 to 100 on-screen we can do this easily with the help of loop.

JavaScript provides us with four kinds of Looping Statements we will learn about these and we will check the example of every Looping Statement. These statements are as follow:

  • for loop
  • while loop
  • do-while loop

Now we will check each statement in detail with example.

for loop:

We use for a loop when we want to run a piece of code for a fixed number of time.

<script>  
for (i=1; i<=10; i++)  
{  
document.write(i + " ")  
}  
</script>

while loop:

we use this statement when we do not know how much time loop will run but we only know about the condition.

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

do-while loop:

This looping statement is the same as while loop expects it will run once even if the condition is false.

<script>  
var num=1;  
do{  
document.write(num + " ");  
num++;  
}while (i<=10);  
</script>
Spread the love