Loops in Javascript

Looping statement is use to execute and repeat a block of statements depending on the condition.

In Javascript, we have the following looping statements – 

  • while
  • do while
  • for

while loop

The while loop first check the condition if the condition is true then the body of the loop statement will be executed. After execution loop checks condition and execute statements until condition will be false.

Syntax –

while(condition){

// Block statements

}

Example –

<script>

var num = 1;

while( num <= 5){

       document.write(num+" ");
       num++;

}

</script>

Output –

1 2 3 4 5

do while loop

do while loop is use to similar as while loop. In basic difference of while loop first check the condition then execute the loop block , but do while loop first execute statement and then check condition . If condition is false in first time then statement will be executed at least one time.

Syntax –

do{

// Block statements

}while(condition);

Example –

<script>

var num = 1;

do{

       document.write(num+" ");
       num++;

}while( num <= 5);

</script>

Output –

1 2 3 4 5

for loop

The for loop is very flexible and is preferable when there is a simple initialization and increment, as it keeps the loop control statements close together and visible at the top of the loop.

Syntax –

for( initialize; condition; increment/decrement ){

// Block statements

}

Example –

<script>

for(var num = 1; num <= 5; num++){
       document.write(num+" ");
}

</script>

Output –

1 2 3 4 5
Spread the love

Related Post

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *