While Loop
The "while" loop in JavaScript is used to execute a block of code as long as a condition is true.
The while loop is a control structure in JavaScript that allows you to execute a block of code as long as a condition is true. It is called a while loop because it continues to execute the code block while the condition is true.
Syntax
Here is the syntax for a while loop in JavaScript:
while (condition) {
// code to be executed
}The condition is a boolean expression that evaluates to either true or false. The code inside the loop is executed as long as the condition is true. If the condition is false, the loop terminates, and the code after the loop is executed.
Examples
Here are some examples of using a while loop in JavaScript:
let count = 0;
while (count < 5) {
console.log(count);
count++;
}In this example, the loop will execute 5 times, and the output will be:
0
1
2
3
4Here is another example:
let x = 10;
while (x > 0) {
console.log(x);
x -= 2;
}In this example, the loop will execute 5 times, and the output will be:
10
8
6
4
2Infinite Loops
It is important to ensure that the condition in a while loop eventually becomes false; otherwise, the loop will continue to execute indefinitely. This is known as an infinite loop and can cause your program to become unresponsive or crash.
Here is an example of an infinite loop:
while (true) {
console.log("This is an infinite loop!");
}In this example, the condition true is always true, so the loop will continue to execute indefinitely.
Conclusion
- The
whileloop is used to execute a block of code as long as a condition is true. - It is important to ensure that the condition in a
whileloop eventually becomes false to avoid infinite loops. - The
whileloop is useful when you do not know in advance how many times the loop will need to execute
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on