SimpleTuts.com

JavaScript while Loop

The while loop in JavaScript repeatedly executes a block of code as long as a specified condition is true.

Here's an example of using a while loop:


// Initialize a counter
var count = 1;

// Initialize an empty array
var squares = [];

// While loop to calculate squares of numbers from 1 to 5
while (count <= 5) {
  var square = count * count;
  squares.push(square);
  count++;
}

// Print the array of squares
console.log(squares); // Output: [1, 4, 9, 16, 25]

Explanation of the example:

All in one Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>While loop</title>
</head>
<body>
    <script>
        var i=0; //Initialisation
        while(i<10){ //Condition 
            document.write("<br>Hello World");
            i++;  //i=i+1;  //Incrementation or Decrementation
        }
    </script>
</body>
</html>
Run Code