3 Example(s) of JavaScript do while statement


Description :

JavaScript do while loop is used to iterate over the statements, Here is the code for do while loop: do{ document.write(" Counter : " + count + "

"); count++; } while (count < 10); See the code snippet:


JavaScript do while statement Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
<body>
<script>
var count = 0;
document.write("Here is the start of loop: " + "<br />");

do{
 document.write(" Counter : " + count + "<br />");
 count++;
} while (count < 10);

document.write ("End of loop!");
</script>
</body>
</html>

Output

Description :

Example of JavaScript do-while loop:


JavaScript do while statement Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
<script>
    var i = 10; 
    do {
        document.write(i + " ");
        i++;
     } while (i < 10);
 </script>
</body>
</html>

Output

Description :

Example of JavaScript do-while loop calculating the sum of numbers:


JavaScript do while statement Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
<button type="button" onclick="calculateSum()">Show the sum</button>
<script>
  function calculateSum()
  {
     var sum = 0;
     var number = 1;

     do {
         sum += number;         
         number++;              
    } while (number <= 50);   

   alert("Sum = " + sum);
 }
</script>
</body>
</html>

Output