# WHILE loops in JavaScript

In 
Published 2022-12-03

This tutorial explains to you how you can use 'while' loops in JavaScript. The 'while' loop (statement) is very used in JavaScript.

# DO ... WHILE loop in JavaScript

Here is the code for testing do...while in JavaScript :

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"> 
</head>
 
<body bgcolor="#E9F3C5">
 
    <div id="parentDiv">   Information o parent div.
       <div id="childDiv1">   >>>>> Information on child div 1</div>
        
       <div id="childDiv2">   >>>>> Information on child div 2</div>
   </div>
 
    <script type="text/javascript">
 
      var i = 0;
      var parent = document.getElementById('parentDiv');
      var child = document.getElementById('childDiv2');
      var text = document.createTextNode("New Text ");
   
      do {
         i += 1;
         text = document.createTextNode("Text " +i+ " / ");
         parent.insertBefore(text, child); 
         } while (i < 5);
 
    </script>
     
</body>
</html>

And here is the result of "do ... while" loop in javascript:

# WHILE loop in JavaScript

Here is the code for testing while in JavaScript :

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"> 
</head>
 
<body bgcolor="#E9F3C5">
 
    <div id="parentDiv">   Information o parent div.
       <div id="childDiv1">   >>>>> Information on child div 1</div>
        
       <div id="childDiv2">   >>>>> Information on child div 2</div>
   </div>
 
    <script type="text/javascript">
 
      var i = 0;
      var parent = document.getElementById('parentDiv');
      var child = document.getElementById('childDiv2');
      var text = document.createTextNode("New Text ");
   
      while (i < 5) {
         i += 1;
         text = document.createTextNode("Text " +i+ " / ");
         parent.insertBefore(text, child); 
         } ;
 
    </script>
     
</body>
</html>

And here is the result of while loop in javascript: