fbpx
April 6, 2020
javascript while loop

JavaScript While loop | Understanding the Use of The While Loop

In this tutorial we will be looking at the JavaScript while loop which entails how to make use of the while loop when coding in JavaScript. In our previous tutorial we looked at JavaScript switch case and we explained how to use the switch case for the right purpose. If you haven’t gone through the tutorial you can do so using the link below

Read previous tutorial on: Introduction to JavaScript Switch Case

JavaScript While Loop

The while loop is used to perform an action over and over again. Sometimes when coding, developers come across situations where they need to perform a certain action over and over again for a specific amount of time. Such situations can be achieved only with the use of JavaScript While Loop.

While Loop Flow Chart

JavaScript While loop
while loop Flow Chart

The while loop is use to carry out an action repeatedly provided a condition is still valid. For example we can set

X= 0

and keep increasing it by 1 till it gets to 10.

then we say for every situation where X is less than 10 we should print out its current value. so every increase in value of X by 1 we print out the current value till the value of X gets to 9

Example using JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
   <title>THE WHILE LOOP </title>
</head>
<body>
   <script>
      var count = 0;
      while (count < 10 ) {
         document.write('counting..... ' + count + '</br>');
         count++;
      }
      
   </script>
   
</body>
</html>

RESULT

THE WHILE LOOP

JavaScript Do While Loop Flow Chart

JavaScript While loop
Do while loop Flow Chart

The do While loop executes the first action before checking if the expression is valid. If the expression is valid, it continues executing the repeated action until the expression becomes invalid.

Example

<!DOCTYPE html>
<html lang="en">
<head>
   <title>THE DO WHILE LOOP </title>
</head>
<body>
   <script>
      var count = 0;
      do{ document.write('lets start counting...' + count + "</br>" );
      count++;}
      while (count < 10 );
   </script>
   
</body>
</html>

RESULT

THE DO WHILE LOOP

CONCLUSION

The while loop and Do while loop are quit similar but with the help of this tutorial we hope you have understood the difference and how to use each of them when coding in JavaScript.

NEXT TUTORIAL: JAVASCRIPT FOR LOOP

Leave a Reply

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