JavaScript Roadmap — Day 21: For Loops — Repeat Code Efficiently

 

JavaScript · Day 21 of 180 · Beginner Phase

For Loops — Repeat Code Efficiently

Stop writing the same code over and over. For loops let you repeat operations, process arrays, and build complex patterns with just a few lines. Master loops and you can handle any repetitive task.

Day 21 / 180
Beginner Phase
🕐 14 min read
💻 8 code examples
🎯 3 practice tasks

Here is the code that shows why loops are essential:

Without loops — repetitive and painful
// ❌ Without a loop — repeating the same code
console.log("Count: 1");
console.log("Count: 2");
console.log("Count: 3");
console.log("Count: 4");
console.log("Count: 5");
// What if you need 100? Or 1000? 😰

// ✅ With a for loop — 3 lines, works for any number
for (let i = 1; i <= 5; i++) {
  console.log(`Count: ${i}`);
}
// Change 5 to 1000 and it just works! 🎉

The for loop is one of the most powerful tools in programming. It takes a repetitive task and turns it into a clean, reusable structure. Today I'll show you exactly how for loops work, from basic counting to complex nested patterns. By the end, you'll never write repetitive code again.

1. The Problem — Repetitive Code

Imagine you need to log numbers 1 to 100. Without loops, you'd write 100 console.log statements. With a loop, you write just 3 lines. Loops solve the repetition problem:

The Repetition Problem
// Without a loop — 100 lines of this would be terrible!
console.log("1");
console.log("2");
console.log("3");
// ... 97 more times ...

// With a loop — just 3 lines!
for (let i = 1; i <= 100; i++) {
  console.log(i);
}

// Same for processing arrays:
let fruits = ["apple", "banana", "cherry", "date"];
for (let i = 0; i < fruits.length; i++) {
  console.log(`Fruit ${i + 1}: ${fruits[i]}`);
}

💡 The insight: Loops embody the DRY principle (Don't Repeat Yourself). Instead of writing the same code multiple times, you write it once and let the loop handle repetition. This makes your code shorter, easier to maintain, and less error-prone.

2. For Loop Syntax — The Three Parts

A for loop has three parts inside parentheses, separated by semicolons: initialization; condition; increment

For Loop Anatomy
// Syntax: for (initialization; condition; increment) { body }
for (let i = 0; i < 5; i++) {
  console.log(i);
}
// Output: 0, 1, 2, 3, 4

// Part 1: let i = 0  → Initialization (runs once at start)
// Part 2: i < 5     → Condition (checked before each iteration)
// Part 3: i++       → Increment (runs after each iteration)

// Different variations:

// Count from 1 to 10
for (let i = 1; i <= 10; i++) {
  console.log(i);
}

// Count backwards from 10 to 1
for (let i = 10; i >= 1; i--) {
  console.log(i);
}

// Count by 2s (even numbers)
for (let i = 0; i <= 20; i += 2) {
  console.log(i);
}

// Count with different variable names
for (let counter = 0; counter < 5; counter++) {
  console.log(counter);
}

3. Looping Through Arrays

The most common use of for loops is processing arrays. Use the array's length property to determine how many times to loop:

Array Looping
// Basic array iteration
let colors = ["red", "green", "blue", "yellow"];
for (let i = 0; i < colors.length; i++) {
  console.log(`Color at index ${i}: ${colors[i]}`);
}

// Calculate sum of array
let numbers = [5, 10, 15, 20];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}
console.log(`Sum: ${sum}`);  // Sum: 50

// Find the largest number
let scores = [45, 72, 88, 91, 67];
let max = scores[0];
for (let i = 1; i < scores.length; i++) {
  if (scores[i] > max) {
    max = scores[i];
  }
}
console.log(`Highest score: ${max}`);  // Highest score: 91

// Create a new array from existing one
let original = [1, 2, 3, 4];
let doubled = [];
for (let i = 0; i < original.length; i++) {
  doubled.push(original[i] * 2);
}
console.log(doubled);  // [2, 4, 6, 8]

4. Nested Loops — Loops Inside Loops

When you put a loop inside another loop, you get a nested loop. The inner loop completes all its iterations for each iteration of the outer loop. Use different variable names (i, j, k) for each level:

Nested Loops
// Multiplication table
for (let i = 1; i <= 5; i++) {
  let row = "";
  for (let j = 1; j <= 5; j++) {
    row += (i * j) + "\t";
  }
  console.log(row);
}
// Output: 5x5 multiplication table

// Creating a star pattern
for (let i = 1; i <= 5; i++) {
  let stars = "";
  for (let j = 1; j <= i; j++) {
    stars += "⭐";
  }
  console.log(stars);
}
// Output:
// ⭐
// ⭐⭐
// ⭐⭐⭐
// ⭐⭐⭐⭐
// ⭐⭐⭐⭐⭐

// Working with 2D arrays (arrays of arrays)
let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`);
  }
}
⚠️ Performance Note: Nested Loops
If the outer loop runs n times and the inner loop runs m times, the total iterations are n × m. For large datasets, this can be slow. Be mindful when nesting loops with big arrays.

5. Common Loop Patterns

Here are patterns you'll use again and again:

Essential Patterns
// Pattern 1: Sum all elements
let sum = 0;
for (let i = 0; i < arr.length; i++) sum += arr[i];

// Pattern 2: Find maximum/minimum
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
  if (arr[i] > max) max = arr[i];
}

// Pattern 3: Count occurrences
let count = 0;
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === target) count++;
}

// Pattern 4: Reverse an array
let reversed = [];
for (let i = arr.length - 1; i >= 0; i--) {
  reversed.push(arr[i]);
}

// Pattern 5: Filter elements
let filtered = [];
for (let i = 0; i < arr.length; i++) {
  if (arr[i] > 10) filtered.push(arr[i]);
}

// Pattern 6: Transform each element
let transformed = [];
for (let i = 0; i < arr.length; i++) {
  transformed.push(arr[i] * 2);
}

// Pattern 7: Check if any element satisfies condition
let found = false;
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === target) {
    found = true;
    break;  // exit loop early when found
  }
}

6. Common Mistakes to Avoid

Mistakes & Fixes
// ❌ MISTAKE 1: Infinite loop (condition never false)
for (let i = 0; i >= 0; i++) {  // i will always be >= 0
  console.log(i);  // runs forever! 💀
}

// ✅ FIX: Ensure condition eventually becomes false
for (let i = 0; i < 10; i++) {  // stops when i reaches 10
  console.log(i);
}

// ❌ MISTAKE 2: Off-by-one error
let arr = ["a", "b", "c"];
for (let i = 0; i <= arr.length; i++) {  // should be <, not <=
  console.log(arr[i]);  // last iteration gives undefined
}

// ✅ FIX: Use < for arrays (0 to length-1)
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

// ❌ MISTAKE 3: Using var instead of let in loops
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (not 0, 1, 2!)

// ✅ FIX: Use let for block scope
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2 ✅

// ❌ MISTAKE 4: Modifying array while looping
let items = [1, 2, 3, 4];
for (let i = 0; i < items.length; i++) {
  items.splice(i, 1);  // removing element while looping
}
// Items not properly cleared!

// ✅ FIX: Loop backwards when removing
for (let i = items.length - 1; i >= 0; i--) {
  items.splice(i, 1);
}

7. Try It Yourself — Loop Playground

Experiment with loops below. Change the start, end, and step values to see how the loop behaves.

✏️ Loop Playground — See Loops in Action
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Try different start, end, and step values!

8. Practice Tasks

Task 1 — Easy: Sum from 1 to N

Write a function sumUpTo(n) that uses a for loop to calculate the sum of all numbers from 1 to n. Test with n = 10 (should return 55) and n = 100 (should return 5050).

Task 2 — Medium: FizzBuzz

Write a program that loops from 1 to 100. For multiples of 3, print "Fizz". For multiples of 5, print "Buzz". For multiples of both 3 and 5, print "FizzBuzz". Otherwise, print the number.

Task 3 — Hard: Find Prime Numbers

Write a function findPrimes(limit) that returns an array of all prime numbers up to the limit. Use nested loops: outer loop for each number, inner loop to check divisibility. Test with limit = 50.

Next Lesson
Day 22 — While and Do-While Loops
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts