While Loop
JavaScript While Loop
A while
loop is another type of control flow statement in programming that repeatedly executes a block of code as long as a specified condition is true. The loop continues to execute until the condition becomes false. The basic syntax of a while
loop is as follows:
while (condition) {
// Code to be executed as long as the condition is true
}
Here's a simple example of a while
loop that prints the numbers 1 to 5:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
In this example:
i
is initialized to 1 before thewhile
loop.- The condition
i <= 5
is checked before each iteration. If it evaluates to true, the code inside the loop is executed. i++
increments the value ofi
after each iteration.
The loop will print the numbers 1 to 5, similar to the for
loop example.
Examples:
Iterating Over an Array:
const colors = ["red", "green", "blue"];
let index = 0;
while (index < colors.length) {
console.log(colors[index]);
index++;
}
Infinite Loop (Be Careful!):
let counter = 0;
while (true) {
console.log(counter);
counter++;
if (counter === 5) {
break; // Ensure the loop doesn't run indefinitely
}
}
Using continue
and break
:
let num = 1;
while (num <= 10) {
if (num % 2 === 0) {
num++;
continue; // Skip even numbers
}
console.log(num);
if (num === 7) {
break; // Exit the loop when num is 7
}
num++;
}
while
loops are useful when the number of iterations is not known in advance or when the loop should continue until a specific condition is met. It's important to ensure that the condition eventually becomes false to avoid infinite loops.