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
while Loop
do..while Loop
for Loop
while Loop
while Loopdo..while Loopfor 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:
var count = 1;: Initializes a variablecountto1.var squares = [];: Initializes an empty arraysquaresto store squared values.while (count <= 5) { ... }: Executes the block of code inside thewhileloop as long ascountis less than or equal to5.- Inside the
whileloop:var square = count * count;: Calculates the square ofcount.squares.push(square);: Adds the calculated square to thesquaresarray.count++;: Incrementscountby1for the next iteration.
console.log(squares);: Prints the arraysquarescontaining squared values from 1 to 5.
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