While, Do-While, and For Loops in JavaScript

JavaScript offers three different types of loops: while, do-while, and for. Loops are a crucial component of programming.

It is simpler to carry out repeated operations in your code by using loops, which enable you to repeat a block of code numerous times. We’ll talk about the various loop types in JavaScript in this post, along with some tips on how to use them efficiently.

In this tutorial, I show the different types of loops in JavaScript and how to use them effectively in your code.

While, Do-While, and For Loops in JavaScript


Contents

  1. while loop
  2. do-while loop
  3. for loop
  4. Conclusion

1. while loop

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

Loop continuously 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 loop

The do-while loop is similar to the while loop.

The basic difference is –

while loop first checks the condition and then executes the loop block, but do-while loop first executes the statement and then checks the 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 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

4. Conclusion

Each type of loop has its own distinct features and advantages, and selecting the appropriate type of loop is dependent on the task. You may develop more efficient and streamlined applications if you understand how to use these loops properly in your code.

If you want your script to execute at least one time whether a condition is true or false then use the do-while loop.

With for loop, you can define a variable, condition,  and increment/decrement variable in a single line.

If you found this tutorial helpful then don't forget to share.

Leave a Comment