A while loop repeatedly executes a block of code as long as a specified condition remains true. It's one of the fundamental loop structures in JavaScript used for iteration.

💡 Basic Syntax
while (condition) {
// code to run
}
The condition is evaluated before each iteration. If it is true, the loop body runs. If false, the loop stops.
📌 Deep Dive: Counting from 1 to 5
let counter = 1;
while (counter <= 5) {
console.log(counter);
counter++;
}
2
3
4
5
Notice the importance of updating the counter variable inside the loop to avoid an infinite loop.
⚠️ Beware of Infinite Loops
If the loop condition never becomes false, the loop will run forever, potentially crashing your program. Always ensure the condition will eventually fail.
| While Loop | For Loop |
|---|---|
| Condition checked before each iteration | Initialization, condition, and increment in one line |
| Good when number of iterations is unknown | Ideal when iterations count is known |
| Separate increment step required inside loop | Increment included in loop header |
Typical use cases for while loops include:
- Waiting for a condition to change dynamically
- Reading data until no more is available
- Repeating tasks until user input or external changes
📌 Deep Dive: Prompt Until Valid Input
let input;
while (!input) {
input = prompt("Enter your name:");
}
console.log("Hello, " + input + "!");
💡 Important
Always ensure the loop’s condition will eventually evaluate to false to avoid freezing the program.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What happens if the condition in a while loop never becomes false?
Question 2 of 2
Which statement about while loops is true?
Loading results...