JS Loop While
In this page:
while (condition) {
// loop body
}
do {
// loop body
} while (condition);
The while Loop
A while loop checks its condition before running its block, and continues repeating that block for as long as the condition remains true, stopping the moment it becomes false.
उदाहरण: The while Loop
// Declare the variable `i`, set to `0`
// Declare the variable `i`, set to `0`
let i = 0;
// Keep looping while `i < 3` holds
// Keep looping while `i < 3` holds
while (i < 3) {
// Print `i` to the console
// Print `i` to the console
console.log(i);
i++;
}
The do...while Loop
A do...while loop runs its block of code first, before checking the condition, guaranteeing the block executes at least once even if the condition is false from the very start.
उदाहरण: The do...while Loop
let i = 5;
do {
console.log(i);
i++;
} while (i < 3); // runs once even though condition is false
while vs for
for loops are generally preferred when the number of iterations is known ahead of time, while while loops are better suited to situations where the stopping condition depends on something that can only be checked during the loop itself.
उदाहरण: while vs for
// for: iterations known ahead of time
for (let i = 0; i < 3; i++) console.log(i);
// while: stopping point depends on runtime state
let n = 10;
while (n > 1) n = n / 2;
console.log(n);
Avoiding Infinite Loops
An infinite loop occurs when a loop's condition can never become false, causing the code to run forever and typically freezing the browser tab, careful review of the loop's update logic is the best defense.
उदाहरण: Avoiding Infinite Loops
// Avoid this - infinite loop, condition never becomes false:
// let i = 0;
// while (i < 5) { console.log(i); }
let i = 0;
while (i < 5) {
console.log(i);
i++; // update makes condition eventually false
}
When to Use while
while loops shine in situations like waiting for a condition to change during processing, repeatedly asking for valid input, or working through a data structure until it's empty, cases where the stopping point genuinely can't be known in advance.
उदाहरण: When to Use while
// Declare the variable `queue`, set to `[1, 2, 3]`
// Declare the variable `queue`, set to `[1, 2, 3]`
let queue = [1, 2, 3];
// Keep looping while `queue.length > 0` holds
// Keep looping while `queue.length > 0` holds
while (queue.length > 0) {
// Print `queue.shift()` to the console
// Print `queue.shift()` to the console
console.log(queue.shift());
}
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS Dates
- JS Math
- JS Conditionals
- JS Switch
- JS Loop For
- JS Loop While
- JS Iterables
- JS Sets
- JS Maps
- JS typeof
- JS Type Conversion
- JS Destructuring
- JS Arrow Functions
- JS Classes
- JS Modules
- JS Promises
- JS Async/Await
- JS DOM
- JS DOM Methods
- JS Events Advanced
- JS DOM Navigation
- JS DOM Collections
- JS Async Callbacks
- JS Async Parallel
- JS Date Set
- JS Set Logic