JavaScript while loop

The JavaScript while loop is a control structure that allows you to iterate a set of instructions until a given condition is met. The while loop consists of two parts: the while keyword and the condition that must be met for the loop to end.

Here's the basic syntax of the JavaScript while loop:

1while (condition) { 2 // code to be executed 3}

In this example, the condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop continues. If the condition is false, the loop terminates and the code after the loop is executed.

Here's an example of how to use the while loop to print the first 10 positive numbers:

1let i = 1; 2 3while (i <= 10) { 4 console.log(i); 5 i++; 6} 7 8// Output: 9// 1 10// 2 11// 3 12// 4 13// 5 14// 6 15// 7 16// 8 17// 9 18// 10

In this example, the i variable is used to keep track of the current number being processed in each iteration of the loop. The while loop continues as long as i is less than or equal to 10. The i++ statement is used to increment i by 1 after each iteration of the loop.

The JavaScript while loop is useful when you need to repeat a set of instructions an unknown number of times, or until a certain condition is met. You can use the while loop to perform tasks such as printing values, counting elements, or updating values.