While Loops
In JavaScript, a while loop is used to repeat a block of code while a certain condition is true. It allows us to continuously execute a set of statements until the condition becomes false.
Here's the basic syntax of a while loop:
1while (condition) {
2 // code to be executed
3}
The condition is evaluated before each iteration. If the condition is true, the code inside the loop is executed. Afterward, the condition is re-evaluated. If the condition is still true, the loop continues to iterate. If the condition is false, the loop stops, and the program continues with the next statement after the loop.
Here's an example that demonstrates the usage of a while loop:
1let num = 1;
2
3while (num <= 10) {
4 console.log(num);
5 num++;
6}
In this example, we initialize the variable num
with the value 1
. The while loop continues to execute as long as num
is less than or equal to 10
. Inside the loop, we print the value of num
and increment its value by 1 using the num++
statement.
While loops are useful when the number of iterations is not known in advance and depends on a condition. They allow us to repeatedly execute a block of code until a desired outcome is achieved.
Your turn to practice using a while loop! Try writing a while loop that prints the numbers from 1 to 10 in reverse order.
xxxxxxxxxx
// Example of a while loop
let count = 1;
while (count <= 5) {
console.log(`Count: ${count}`);
count++;
}