A for loop in JavaScript is a control structure used to repeat a block of code a specific number of times. It is commonly used to iterate over arrays or execute code multiple times with a counter.

💡 Basic Syntax
for (initialization; condition; update) {
// code to execute
}
Explanation of the parts:
- Initialization: Sets up a counter variable (runs once at the start).
- Condition: A boolean expression checked before each iteration; the loop runs while true.
- Update: Changes the counter after each iteration (usually increment or decrement).
| Part | Purpose |
|---|---|
| Initialization | Set starting point (e.g., let i = 0) |
| Condition | Loop continues if true (e.g., i < 5) |
| Update | Change counter (e.g., i++) |
📌 Deep Dive: Counting with a For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
1
2
3
4
The loop above starts i at 0, runs while i < 5, and increments i by 1 each time, printing numbers 0 through 4.
💡 Common Uses
- Iterating over arrays using an index.
- Repeating tasks a fixed number of times.
📌 Deep Dive: Loop through an Array
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
banana
cherry
⚠️ Avoid Infinite Loops
If the condition never becomes false, the loop runs forever and can crash your program. Always ensure the update changes the condition eventually.
For example, this loop will never end because i is never updated:
📌 Deep Dive: Infinite Loop Example (Avoid!)
for (let i = 0; i < 5;) {
console.log(i);
// Missing i++ update — infinite loop!
}
💡 Alternative: Looping Backwards
You can count downwards by initializing with a higher number and decrementing:
📌 Deep Dive: Counting Down
for (let i = 5; i > 0; i--) {
console.log(i);
}
4
3
2
1
💡 Summary
- For loops repeat code a known number of times.
- They consist of initialization, condition, and update expressions.
- Commonly used for array iteration or counting.
- Beware of infinite loops by ensuring the condition will eventually be false.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which part of the for loop controls how many times the loop runs?
Question 2 of 2
What will happen if you forget to update the counter variable inside a for loop?
Loading results...