Topic 30 of 87
while Loop
Overview
The while loop loops through a block of code as long as a specified condition evaluates to true.
You should use a for loop when you know exactly how many times you want to iterate (e.g., looping 10 times). You should use a while loop when you don't know the exact count, but you know the condition that should stop the loop.
Syntax
Basic while loop
javascript
let count = 0;
while (count < 3) {
console.log("Count is: " + count);
// CRITICAL: You must manually update the condition!
count++;
}Common Pitfalls
- Forgetting to update the variable that the condition depends on inside the loop block. This guarantees an infinite loop, freezing the application.
Interview Questions
Q:
When would you choose a
while loop over a for loop?A:
A for loop is ideal for iterating a known number of times (like iterating over an array). A while loop is ideal when the number of iterations is unknown, such as continually polling a server until a specific job status is 'Complete'.
Real-World Example
Traversing a linked list or navigating up the DOM tree until you find a specific parent element.
example
javascript
let currentElement = element;
while (currentElement.parentElement !== null) {
if (currentElement.className === 'target-container') break;
currentElement = currentElement.parentElement;
}Check Your Knowledge
Test your understanding of while Loop with these quick questions.