while Loop
Introduction to 'while' Loop
In JavaScript, a `while` loop is a type of loop that executes a block of code repeatedly as long as a specified condition is true. It is called a "while" loop because it repeats the code until the condition becomes false. The `while` loop is useful when you want to execute a block of code an unknown number of times.
Syntax
The syntax of a `while` loop is as follows:
while (condition) {
// code to be executed
}
The condition is evaluated before each iteration. If the condition is true, the code inside the loop is executed. Once the condition becomes false, the loop stops executing and the program continues with the next line of code after the loop.
Example
Let's say we want to print numbers from 1 to 5 using a `while` loop:
let count = 1; // initializationwhile (count <= 5) { // condition
console.log(count);
count++; // modification
}
Output:
1 2 3 4 5
In this example, we initialize the `count` variable to 1. The loop continues to execute as long as `count` is less than or equal to 5. Inside the loop, we print the value of `count` and then increment it by 1 using the `count++` statement.
Comparison between the while and the do-while loop
The do-while loop executes the content of the loop once before checking the condition of the while loop. While the while loop will check the condition first before executing the content.
While Loop
- It is an entry condition looping structure.
- The number of iterations depends on the condition mentioned in the while block.
- The block control condition is available at the starting point of the loop.
- The block of code is controlled at starting.
Do-While Loop
- It is an exit condition looping structure.
- The number of iterations will be at least one irrespective of the condition.
- The block control condition is available at the endpoint of the loop.
- The block code is controlled at the end.
Key Takeaways
- The `while` loop executes a block of code as long as a specified condition is true.
- The condition is evaluated before each iteration.
- The loop stops executing when the condition becomes false.
- Make sure to include a mechanism to modify the condition inside the loop, to avoid an infinite loop.
- The `while` loop is useful when the number of iterations is not known beforehand.
Comments
Post a Comment