for Loop
The for loop is the most common loop in programming. It repeats a block of code a specific number of times. Use it for counting, iterating arrays, and any task that needs repetition.
for Loop Structure
- for (init; condition; update) { } — Three parts: initialization, condition check, update
- init — Runs once before the loop starts: let i = 0
- condition — Checked before each iteration. Loop stops when false: i < 10
- update — Runs after each iteration: i++ (increment by 1)
- Common pattern — for (let i = 0; i < array.length; i++) { ... }
- Use cases — Counting, iterating arrays by index, repeating operations N times
for Loop Code
// Count 1 to 5
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// Iterate an array
const fruits = ["Apple", "Banana", "Cherry", "Date"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
// Count backwards
for (let i = 5; i >= 1; i--) {
console.log("Countdown:", i);
}
console.log("🚀 Launch!");
// Skip by 2
for (let i = 0; i <= 10; i += 2) {
console.log("Even:", i); // 0, 2, 4, 6, 8, 10
}
// Sum of numbers 1-100
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log("Sum 1-100:", sum); // 5050Try It Yourself: Multiplication Table
Tip
Tip
Always use let (not var or const) for the loop variable: for (let i = 0; ...). let keeps the variable scoped to the loop. Using var causes it to leak outside, and const would error on i++ since it can't be reassigned.
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Using <= instead of < with array.length causes an off-by-one error. for (let i = 0; i <= array.length; i++) accesses array[array.length] which is undefined. Always use i < array.length for zero-based arrays.
Practice Task
Note
Practice for loops: (1) Print numbers 1-20. (2) Sum all even numbers from 1-100. (3) Print a countdown from 10 to 1 followed by 'Launch!'. (4) Generate the 7 times table from 1-12.
Quick Quiz
Key Takeaways
- The for loop is the most common loop in programming.
- for (init; condition; update) { } — Three parts: initialization, condition check, update
- init — Runs once before the loop starts: let i = 0
- condition — Checked before each iteration. Loop stops when false: i < 10