JavaScript provides a while
loop to execute code repeatedly until a specified condition is no longer true. Unlike the for
loop, it only requires a condition expression.
Syntax
while (condition) {
// Code to execute while condition is true
}
Example: Basic While Loop
var i = 0;
while (i < 5) {
console.log(i);
i++;
}
Output:
0 1 2 3 4
Important Considerations
Ensure the condition expression is appropriate and include increment or decrement statements inside the loop to prevent infinite execution.
JavaScript Do-While Loop
The do-while
loop is a variation of the while
loop. The key difference is that it evaluates the condition after executing the code block, ensuring the loop runs at least once.
Syntax
do {
// Code to execute at least once
} while (condition);
Example: Do-While Loop
var i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Output:
0 1 2 3 4
Example: Do-While Loop Executing Even When Condition is False
var i = 0;
do {
console.log(i);
i++;
} while (i > 1);
Output:
0
Points to Remember
- The
while
loop executes code repeatedly while the condition remains true. - The
do-while
loop guarantees at least one execution even if the condition is false. - Always include an increment/decrement statement to avoid infinite loops.