Lesson 39 of 48
81%
For Loop
A for loop is a counting machine.
It has a start, a stop test, and a step.
Think of climbing stairs. Start at step 1. Stop at the top. Add one each time.
1
The three parts
2
Looping over arrays
3
Counting down
4
Nested for loops
The three parts
First part sets the starter.
Second part checks if we should keep going.
Third part updates the counter.
javascript
Read it like a story
Start with i = 0.
While i < 3 is true, run the block.
After each round, do i++.
javascript
Loop through an array
Use i as an index into the list.
Stop before length.
javascript
Count down
You can subtract instead of add.
javascript
Nested loops
A loop inside a loop can build grids.
Keep variable names clear so you do not mix counters.
javascript
Tip: Off by one bugs are common. Check whether you want < length or <= lastNumber.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.