While, Do-While, and For Loops in JavaScript

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

There are following types of loops in JavaScript –

  • while
  • do while
  • for


Contents

  1. while
  2. do while
  3. for

1. while

The while loop first checks the condition if the condition is true then the executes the block code.

Loop continues executed until the condition is true.

Syntax –

while(condition){

// Block statements

}

Example –

<script>

var num = 1;

while( num <= 5){

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

}

</script>

Output –

1 2 3 4 5

2. do while

do while loop is similar as while loop.

The basic difference is –

while loop first checks the condition then execute the loop block, but do while loop first executes statement and then check condition.

If the condition is false for the first time then the 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

3. for

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

Related Post

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  

Be First to Comment

Leave a Reply

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