The while statement is a loop construct in JavaScript that repeatedly executes a block of code as long as a specified condition evaluates to true. Unlike the do...while loop, the while loop checks the condition at the beginning of each iteration, and if the condition is false initially, the loop will not execute at all.
Syntax:
while (condition) {
// Code to be executed
}
Exmaple
let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;
}
/* Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
*/
It’s essential to ensure that the condition in a while loop eventually becomes false; otherwise, the loop will continue indefinitely, resulting in an infinite loop.