While Loop Execution Flow
You'll learn: How a while loop checks its condition before each iteration and decides when to stop.
The Checking Process
A while loop follows a strict sequence every time it runs:
- Check the condition — Before anything happens (even the first time), JavaScript evaluates the condition expression
- If true — Execute the loop body, then go back to step 1
- If false — Skip the loop body entirely and continue with code after the loop
Think of it like a security guard at a door: every single time you want to enter (even your first attempt), the guard checks your credentials. If you pass, you go through and then have to check again. The moment you fail, you're done—no entry.
Why "Before Each Iteration" Matters
let count = 5;
while (count < 3) {
console.log(count);
count++;
}
// Prints nothing! The condition is false from the start.
The loop body never runs because the condition fails on the very first check. The while loop doesn't execute "at least once"—it's entirely dependent on that initial condition.
The Loop Never Executes vs Executes Once
let x = 1;
while (x < 2) {
console.log("Runs once");
x = 10; // Condition will fail next check
}
// Prints: "Runs once"
// Then x < 2 is false, loop terminates
After the body runs and x becomes 10, control returns to the condition check. Since 10 < 2 is false, the loop terminates immediately.
Key Takeaway: A while loop always checks its condition before each iteration, including the first one—if the condition is false initially or becomes false after any iteration, the loop terminates immediately without executing the body again.