JavaScript while loop

The while loop in JavaScript is used to continually run a block of code while a specific circumstance is true. The basic syntax is as follows:

while (condition) { // code to be executed while the condition is true }

The condition is an expression that is evaluated at the beginning of each iteration of the loop. If the condition is true, the code inside the loop block is executed. Once the code inside the loop block is finished executing, the condition is evaluated again, and the process repeats until the condition is no longer true.

This is an example of the while loop statement:

let count = 0; while (count < 6) { console.log(count); count++; }

In this example, the while loop executes as long as count is less than 6. During each iteration of the loop, the current value of count is printed to the console using console.log(), and then count is incremented by 1 using the ++ operator. The loop will repeat until count reaches 6, at which point the condition will no longer be true, and the loop will terminate.

Note that if the condition is never false, the while loop will continue to execute indefinitely, resulting in an infinite loop. It's important to ensure that the condition will eventually become false in order to prevent this from happening.

Last updated