0
0
Javascriptprogramming~10 mins

While loop in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop
Initialize variable
Check condition?
NoEXIT
Yes
Execute loop body
Update variable
Back to Check
The while loop starts by checking a condition. If true, it runs the loop body, updates variables, then checks again. It stops when the condition is false.
Execution Sample
Javascript
let count = 0;
while (count < 3) {
  console.log(count);
  count++;
}
This code prints numbers 0, 1, 2 by repeating the loop while count is less than 3.
Execution Table
IterationcountCondition (count < 3)ActionOutput
10truePrint 0, count = count + 10
21truePrint 1, count = count + 11
32truePrint 2, count = count + 12
43falseExit loop
💡 count reaches 3, condition 3 < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
count01233
Key Moments - 2 Insights
Why does the loop stop when count is 3 even though the code inside the loop increases count?
The condition is checked before the loop body runs each time. When count is 3, the condition count < 3 is false, so the loop does not run again (see execution_table row 4).
What happens if we forget to increase count inside the loop?
The condition will always be true, causing an infinite loop because count never changes (no progress in variable_tracker).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of count during the 2nd iteration?
A1
B2
C0
D3
💡 Hint
Check the 'count' column in execution_table row 2
At which iteration does the condition become false and the loop stops?
A3
B4
C2
D1
💡 Hint
Look at execution_table row 4 where condition is false
If we change the condition to count < 5, how many times will the loop run?
A3 times
B4 times
C5 times
D6 times
💡 Hint
The loop runs while count is less than the condition number, see variable_tracker for count changes
Concept Snapshot
while (condition) {
  // code runs while condition is true
}

- Condition checked before each loop
- Loop stops when condition is false
- Update variables inside loop to avoid infinite loops
Full Transcript
A while loop in JavaScript repeats code as long as a condition is true. It starts by checking the condition. If true, it runs the loop body, then updates variables. This repeats until the condition becomes false. For example, starting with count = 0, the loop prints count and increases it by 1 each time. When count reaches 3, the condition count < 3 is false, so the loop stops. Remember to update variables inside the loop to avoid infinite loops.