JavaScript While Loop – Repeat Code Efficiently
The while loop in JavaScript is used to execute a block of code repeatedly as long as a specified condition evaluates to true.
1. Syntax of while Loop:
while (condition) {
// Code to execute as long as the condition is true
}
Explanation:
- condition: An expression evaluated before each iteration. If the condition is
true, the loop runs; otherwise, it stops.
2. Basic Example of while Loop:
let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;
}
Output:
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
Explanation:
- The loop starts with
count = 0and incrementscountby 1 in each iteration. - The loop runs as long as
count < 5.
3. Example with User Input:
let input;
while (input !== "stop") {
input = prompt("Type 'stop' to end the loop:");
console.log("You entered: " + input);
}
Explanation:
- The loop continues to prompt the user for input until they type
"stop".
4. Infinite Loop (Use with Caution):
A while loop can become an infinite loop if the condition never evaluates to false. This can cause the browser or script to freeze.
while (true) {
console.log("This will run forever unless stopped!");
}
Note: Ensure that the loop has an exit condition to avoid infinite loops.
5. while Loop with break:
You can use the break statement to exit the loop prematurely.
let count = 0;
while (count < 10) {
console.log("Count: " + count);
if (count === 5) {
break;
}
count++;
}
Output:
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
6. while Loop with continue:
The continue statement skips the current iteration and moves to the next one.
let count = 0;
while (count < 5) {
count++;
if (count === 3) {
continue;
}
console.log("Count: " + count);
}
Output:
Count: 1 Count: 2 Count: 4 Count: 5
Explanation:
- When
countequals 3, thecontinuestatement skips the rest of the loop body for that iteration.
7. Using while Loop for Array Iteration:
let fruits = ["Apple", "Banana", "Cherry"];
let index = 0;
while (index < fruits.length) {
console.log(fruits[index]);
index++;
}
Output:
Apple Banana Cherry
Explanation:
- The loop iterates through the array elements until all elements are printed.
Conclusion:
- The
whileloop is ideal for situations where the number of iterations depends on a dynamic condition. - It is important to ensure that the condition eventually becomes
falseto avoid infinite loops. - Using
breakandcontinueprovides additional control over loop execution.