SimpleTuts.com

JavaScript while Loop

JavaScript Loops

JavaScript loops are a fundamental concept in programming, allowing you to execute a block of code multiple times based on a given condition. They are essential for tasks that require repeated actions, such as iterating over arrays, processing data, or automating repetitive tasks.

Types of Loops in JavaScript

  1. while Loop
  2. do..while Loop
  3. for Loop

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