For Loop
Suppose your teacher asks you to write "I will not talk in class" 100 times as punishment. 😅
In JavaScript, you could write:
That is boring, slow, and full of chances for mistakes. What if it was 10,000 times?
This is where loops help. A loop lets you repeat code as many times as you want, with just a few lines.
Just 3 lines, and the work is done 100 times! 🎉
What Is a For Loop?
A for loop repeats a block of code a fixed number of times, as long as a condition is true.
It is best used when you know in advance how many times you want to repeat something.
Syntax
for (initialization; condition; update) {
// code to repeat
}
A for loop has three parts inside the brackets, separated by semicolons ;:
| Part | Meaning | Example |
|---|---|---|
| Initialization | Starting point, runs once at the beginning | let i = 1 |
| Condition | Checked before every round. The loop continues while it is true | i <= 5 |
| Update | Runs after every round, usually to move forward | i++ |
Think of it like running laps around a school ground:
- Initialization: Start at lap 1.
- Condition: Keep running while the lap number is 5 or less.
- Update: After each lap, add 1 to the lap count.
Your First For Loop
How It Works, Step by Step
| Step | Value of i | Condition i <= 5 | Action |
|---|---|---|---|
| Start | 1 | — | Initialization |
| Round 1 | 1 | ✅ true | Print "Lap 1", then i++ |
| Round 2 | 2 | ✅ true | Print "Lap 2", then i++ |
| Round 3 | 3 | ✅ true | Print "Lap 3", then i++ |
| Round 4 | 4 | ✅ true | Print "Lap 4", then i++ |
| Round 5 | 5 | ✅ true | Print "Lap 5", then i++ |
| Check | 6 | ❌ false | Loop stops |
The flow:
Initialize → Check condition → Run code → Update → Check condition → Run code → Update → ...
↓ (false)
Exit the loop
Key points:
- The initialization runs only once.
- The condition is checked before every round, including the first one.
- Each round of the loop is called an iteration.
iis just a name. It is short for "index", and developers commonly use it for counters.
More Simple Examples
Counting from 0
In programming, counting often starts from 0.
Notice we used i < 5, not i <= 5. This still runs 5 times (0, 1, 2, 3, 4).
Counting backwards: a rocket launch countdown 🚀
Here, we start high, the condition checks i >= 1, and i-- decreases the value.
Jumping by more than 1
The update doesn't have to be i++. You can jump by any number.
Multiplication table
Adding numbers: sum from 1 to 100
Each round adds the current number to sum, like a piggy bank collecting coins one by one.
Looping Through an Array
One of the most common uses of a for loop is to go through each item of an array.
Remember: array positions (indexes) start from 0.
Key points:
- Start with
i = 0, because the first item is at index 0. - Use
i < fruits.length, not<=. The last index is alwayslength - 1. fruits[i]gives the item at the current position.
Real example: calculating a shopping bill
Finding the highest marks
Here, we combined a for loop with an if statement!
Nested For Loops
You can put a loop inside another loop. For every round of the outer loop, the inner loop runs completely.
Think of a clock: for every 1 hour (outer loop), the minute hand goes around 60 times (inner loop).
Example: star pattern
How it works:
- Row 1: the inner loop runs 1 time.
- Row 2: the inner loop runs 2 times.
- Row 3: the inner loop runs 3 times, and so on.
Example: seats in a cinema hall
This prints 3 × 4 = 12 seats.
Tip: Nested loops can become slow with large numbers. 1000 × 1000 = 1 million rounds! Use them wisely.
Optional Parts of a For Loop
All three parts are optional, but the semicolons are required.
This works, but the normal form is much easier to read. Stick to the standard style.
Infinite Loops ⚠️
If the condition never becomes false, the loop never stops. This is called an infinite loop, and it can freeze your browser or program!
// ❌ DANGER: i keeps increasing, so i >= 1 is always true
for (let i = 1; i >= 1; i++) {
console.log(i);
}
// ❌ DANGER: no condition means it runs forever
for (;;) {
console.log("Help! I can't stop!");
}
How to avoid it:
- Make sure your update moves toward making the condition false.
- Counting up? Use
<or<=. Counting down? Use>or>=.
Why Use let for the Counter?
When you use let i, the variable i exists only inside the loop.
This is good! It keeps your code clean and avoids accidental mistakes. Avoid using var for loop counters.
Common Mistakes to Avoid
❌ Mistake 1: Off-by-one error
Fix: Use i < colors.length.
❌ Mistake 2: Using commas instead of semicolons
for (let i = 0, i < 5, i++) { } // ❌ SyntaxError
for (let i = 0; i < 5; i++) { } // ✅
❌ Mistake 3: Semicolon after the brackets
❌ Mistake 4: Wrong update direction
for (let i = 10; i >= 1; i++) { } // ❌ infinite loop (should be i--)
Stopping or Skipping in a Loop (Preview)
JavaScript has two special keywords to control loops:
breakstops the loop completely.continueskips the current round and moves to the next one.
We will learn them in detail in the Break & Continue lesson.
Quick Summary Table
| Task | Example |
|---|---|
| Count 1 to 5 | for (let i = 1; i <= 5; i++) |
| Count 0 to 4 | for (let i = 0; i < 5; i++) |
| Count backwards | for (let i = 10; i >= 1; i--) |
| Jump by 2 | for (let i = 0; i <= 10; i += 2) |
| Loop through an array | for (let i = 0; i < arr.length; i++) |
Key Takeaways
- A for loop repeats code a fixed number of times, saving you from writing the same lines again and again.
- It has three parts: initialization (start), condition (when to continue), and update (how to move forward).
- To loop through an array, start at
0and usei < array.length. - Nested loops run the inner loop completely for every round of the outer loop.
- Watch out for infinite loops and off-by-one errors, and always use
letfor the counter.