4 Example(s) of JavaScript While Statement


Description :

In this example, We are starting counter from 0 then the while condition limit till 10 and then add 1 using count++. See the code snippet:


JavaScript 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("Starting Loop ");
         
            while (count < 10){
               document.write("I am : " + count + "<br />");
               count++;
            }
         
            document.write("Loop stopped!");
        
      </script>

</body>
</html>

Output

Description :

JavaScript while loop on array of vehicles. var vehicles = ["Audi", "BMW", "Alto", "Swift"]; var i = 0; var text = ""; while (vehicles[i]) { text += vehicles[i] + "

"; i++; } See the code snippet:


JavaScript While Statement Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>    
<body>
<p id="sample"></p>

<script>
var vehicles = ["Audi", "BMW", "Alto", "Swift"];
var i = 0;
var text = "";
while (vehicles[i]) {
    text += vehicles[i] + "<br>";
    i++;
}
document.getElementById("sample").innerHTML = text;
</script>
</body>
</html>

Output

Description :

Example of JavaScript While Statement:


JavaScript While Statement Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>    
<body>
<p id="sample"></p>

<script>

var i = 0;
var j = 10;
while (i < 100) {
    if (i == j)
        break;
    i++;
}
document.getElementById("sample").innerHTML = i;
</script>
</body>
</html>

Output

Description :

Example of JavaScript while statement:


JavaScript While Statement Example - 4
<!DOCTYPE html>
<html>
<head>

</head>    
<body>
<button onclick="myFunction()">Click it</button>
<p id="sample"></p>

<script>
function myFunction() {
    var sum = 0;
    var number = 1;
    while (number <= 50) {  
      sum += number;        
      number++;             
    }
    alert("Sum = " + sum);  
}
document.getElementById("sample").innerHTML = i;
</script>
</body>
</html>

Output