0
0
Javascriptprogramming~10 mins

Loop execution flow in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Loop execution flow
Initialize counter i=0
Check condition i < 3?
NoEXIT LOOP
Yes
Execute loop body
Update counter i = i + 1
Back to condition check
The loop starts by setting a counter, checks if the condition is true, runs the loop body if yes, then updates the counter and repeats until the condition is false.
Execution Sample
Javascript
for (let i = 0; i < 3; i++) {
  console.log(i);
}
This code prints numbers 0, 1, and 2 by looping while i is less than 3.
Execution Table
Iterationi valueCondition (i < 3)ActionOutput
10truePrint 0, i++0
21truePrint 1, i++1
32truePrint 2, i++2
43falseExit loop
💡 i reaches 3, condition 3 < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 3 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes false at iteration 4 (see execution_table row 4), so the loop exits.
When is the value of i updated during the loop?
i is updated after the loop body runs in each iteration (see execution_table Action column), before the next condition check.
Why does the loop print 0 first instead of 1?
Because i starts at 0 (initialization), and the condition is checked before the loop body, so the first printed value is 0 (see execution_table row 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during the 3rd iteration?
A2
B3
C1
D0
💡 Hint
Check the 'i value' column in the execution_table at iteration 3.
At which iteration does the loop condition become false?
AIteration 3
BIteration 2
CIteration 4
DIteration 1
💡 Hint
Look at the 'Condition (i < 3)' column in the execution_table for when it becomes false.
If we change the loop to i < 4, how many times will the loop run?
A3 times
B4 times
C5 times
D2 times
💡 Hint
Think about how the condition affects the number of iterations, referencing the variable_tracker for i values.
Concept Snapshot
for (let i = 0; i < limit; i++) {
  // loop body
}

1. Initialize counter i
2. Check condition before each iteration
3. Run loop body if true
4. Update counter after body
5. Repeat until condition false
Full Transcript
This visual shows how a for loop runs in JavaScript. It starts by setting a counter i to 0. Then it checks if i is less than 3. If yes, it runs the loop body, printing i. After that, it increases i by 1. This repeats until i reaches 3, when the condition becomes false and the loop stops. The execution table tracks each step, showing i's value, the condition check, the action taken, and the output printed. The variable tracker shows how i changes after each iteration. Common confusions include why the loop stops at 3, when i updates, and why it prints 0 first. The quiz questions help check understanding of these steps.