JavaScript for Loop
The most common loop for counting and iterations
🔢 What is a for Loop?
The for loop is perfect when you know exactly how many times you want to repeat code. It's the most commonly used loop in JavaScript programming.
// Basic for loop syntax
for (initialization; condition; increment) {
// Code to repeat
}
// Example: Count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
for Loop Components
Initialization
Sets up the counter variable
let i = 0 // Start counting from 0
Condition
Checks if loop should continue
i < 10 // Continue while i is less than 10
Increment
Updates the counter after each loop
i++ // Add 1 to i after each iteration
Loop Body
Code that runs each iteration
console.log(i); // Execute this code
🔹 Basic for Loop Examples
Let's see different ways to use for loops:
🔸 Counting Up
// Count from 0 to 4
for (let i = 0; i < 5; i++) {
console.log("Number: " + i);
}
Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
🔸 Counting Down
// Count from 5 down to 1
for (let i = 5; i >= 1; i--) {
console.log("Countdown: " + i);
}
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
🔸 Skip Numbers (Increment by 2)
// Count even numbers from 0 to 10
for (let i = 0; i <= 10; i += 2) {
console.log("Even: " + i);
}
Output:
Even: 0
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10
🔹 for Loop with Arrays
for loops are perfect for working with arrays:
// Loop through array by index
const fruits = ["apple", "banana", "orange", "grape"];
for (let i = 0; i < fruits.length; i++) {
console.log(`Index ${i}: ${fruits[i]}`);
}
// Calculate sum of numbers
const numbers = [10, 20, 30, 40, 50];
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
console.log("Total sum: " + total);
Output:
Index 0: apple
Index 1: banana
Index 2: orange
Index 3: grape
Total sum: 150
🔹 Nested for Loops
You can put for loops inside other for loops:
// Create a multiplication table
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} x ${j} = ${i * j}`);
}
console.log("---"); // Separator
}
// Create a pattern
for (let row = 1; row <= 4; row++) {
let stars = "";
for (let col = 1; col <= row; col++) {
stars += "* ";
}
console.log(stars);
}
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---
*
* *
* * *
* * * *
🔹 Common for Loop Mistakes
❌ Avoid These Mistakes:
-
Off-by-one errors:
Use
i < array.lengthnoti <= array.length - Infinite loops: Make sure the condition eventually becomes false
- Wrong increment: Don't forget to increment the counter
- Modifying array length: Be careful when adding/removing items during loop
✅ Good Practices:
-
Use meaningful variable names:
i,index,count -
Cache array length:
for (let i = 0, len = arr.length; i < len; i++) -
Use
constfor arrays that won't be reassigned -
Consider
for...ofwhen you don't need the index