0
0
Javascriptprogramming~10 mins

For loop in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop
Initialize i=0
Check: i < 5?
NoEXIT
Yes
Execute body
Update: i = i+1
Back to Check
The for loop starts by setting a variable, checks a condition, runs the code inside if true, then updates the variable and repeats until the condition is false.
Execution Sample
Javascript
for (let i = 0; i < 5; i++) {
  console.log(i);
}
This code prints numbers from 0 to 4, one per line.
Execution Table
Iterationi valueCondition (i < 5)ActionOutput
10truePrint 00
21truePrint 11
32truePrint 22
43truePrint 33
54truePrint 44
65falseExit loop
💡 i reaches 5, condition 5 < 5 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
i0123455
Key Moments - 3 Insights
Why does the loop stop when i equals 5?
Because the condition i < 5 becomes false at i = 5, so the loop exits as shown in execution_table row 6.
When is the value of i updated during the loop?
i is updated after executing the loop body, before the next condition check, as seen between each iteration in variable_tracker.
Does the loop print the number 5?
No, because the loop stops before printing when i is 5, confirmed by the exit in execution_table row 6.
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
D4
💡 Hint
Check the 'i value' column in the execution_table at iteration 3.
At which iteration does the loop condition become false?
A5
B6
C4
D1
💡 Hint
Look at the 'Condition (i < 5)' column in execution_table where it changes to false.
If we change the loop to i <= 5, how many times will the loop run?
A4 times
B5 times
C6 times
D7 times
💡 Hint
Think about the condition i <= 5 allowing i to be 5 inside the loop, check variable_tracker for i values.
Concept Snapshot
for (let i = 0; i < limit; i++) {
  // code to repeat
}
- Initialize i once at start
- Check condition before each loop
- Run code if true
- Update i after each loop
- Stop when condition is false
Full Transcript
A for loop in JavaScript starts by setting a variable i to 0. It then checks if i is less than 5. If yes, it runs the code inside the loop, here printing i. After that, it increases i by 1. This repeats until i is 5, when the condition i < 5 becomes false and the loop stops. The loop prints numbers 0 to 4. The variable i changes from 0 up to 5, but the loop stops before printing 5. This process is shown step-by-step in the execution table and variable tracker.