JavaScript While loops are a type of loop statement that allows you to repeatedly execute a block of code as long as a specified condition is true. The syntax for a while loop is as follows:
while (condition) {
// code to be executed
}
Here, the condition is an expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop will be executed. This will continue until the condition becomes false.
Here’s an example that demonstrates the use of a while loop in JavaScript:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
In this example, the loop will execute as long as the value of i
is less than 5. Each time the loop executes, the value of i
will be incremented by 1 and the value of i
will be printed to the console.
It’s important to note that if the condition in a while loop is never false, the loop will continue to run indefinitely, resulting in an infinite loop. Therefore, it’s important to ensure that the condition will eventually become false in order to prevent an infinite loop.