JavaScript For Loop
8 April 2025 | Category: JavaScript
The for
loop is used to repeat a block of code a specific number of times. It is commonly used when you know how many times you want to run the code.
✅ Syntax
for (initialization; condition; increment) {
// Code to execute on each loop
}
- Initialization: runs once, before the loop starts.
- Condition: checked before every loop iteration.
- Increment/Decrement: updates the loop variable after each iteration.
📌 Example: Counting 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
🔄 Loop Breakdown
for (let i = 0; i < 3; i++) {
console.log("Looping!");
}
What happens here:
let i = 0
→ Start withi = 0
.i < 3
→ Loop runs whilei
is less than 3.i++
→ After each loop, increasei
by 1.- Repeats 3 times: when
i
is 0, 1, 2.
❌ Loop Without break
If you forget to update your variable or use a wrong condition, it can cause an infinite loop:
for (let i = 0; i >= 0; i++) {
console.log("Oops! Infinite loop!");
}
Always make sure your loop condition will eventually become false!
🔁 Looping Through an Array
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
apple
banana
cherry
🔁 Reverse Loop
for (let i = 5; i >= 1; i--) {
console.log(i);
}
Output:
5
4
3
2
1
🧪 Nested Loops
You can put one loop inside another to create nested loops:
for (let i = 1; i <= 2; i++) {
for (let j = 1; j <= 2; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
📘 Summary
- Use
for
loops to repeat code a set number of times. - Common for iterating over arrays or counting.
- Be careful with loop conditions to avoid infinite loops.
- Useful for both forward and reverse iterations.