The while
loop in JavaScript allows you to execute a block of code as long as a specified condition evaluates to true
. It's useful for repeating tasks when the number of iterations is not known in advance.
While Loop in JavaScript
Basic Syntax of a While Loop
while (condition) {
// code to be executed
}
In this syntax, the code block inside the while
loop will be executed as long as the condition
is true.
Example of a While Loop
let count = 0;
while (count < 5) {
console.log("Count is: " + count);
count++;
}
In this example, the loop will print the current value of count
to the console until it reaches 5. The count++
statement increments the count by 1 in each iteration.
Using a While Loop for User Input
let input;
while (input !== "exit") {
input = prompt("Enter something (type 'exit' to stop):");
console.log("You entered: " + input);
}
This example demonstrates a while loop that continues to prompt the user for input until they type "exit". The input is then logged to the console.
Infinite Loops
Be cautious when using while
loops, as it's easy to create an infinite loop if the condition never becomes false. For example:
let num = 0;
while (num < 5) {
console.log(num);
// Missing increment here will cause an infinite loop
}
This loop will run indefinitely since num
is never incremented.
Conclusion
The while
loop is a powerful tool in JavaScript for executing code repeatedly based on a condition. However, it's important to ensure that the loop will eventually terminate to avoid infinite loops.