Lesson 7: Loops - Repeating Code

What You'll Learn

  • What loops are and when to use them
  • The for loop for counted repetitions
  • The while and do...while loops
  • The for...of and for...in loops
  • How to control loops with break and continue
  • How to avoid infinite loops

Why This Matters

Loops let you repeat code without typing it multiple times. Need to process 1,000 items? Process each student's grade? Count to 100? Loops make this easy and efficient.

---

Part 1: The for Loop

The for loop is perfect when you know how many times you want to repeat something.

Create a new file: lesson-07/loops.js

Basic for Loop

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

// Output:
// 1
// 2
// 3
// 4
// 5

Understanding for Loop Syntax

for (initialization; condition; increment) {
  // Code to repeat
}

Let's break it down:

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
  1. let i = 1 (initialization): Create a counter variable, set it to 1
  2. i <= 5 (condition): Keep looping while this is true
  3. i++ (increment): After each loop, add 1 to i
  4. { }: The code to repeat

How It Works (Step by Step)

Step 1: i = 1, check 1 <= 5 (true), print 1, then i becomes 2
Step 2: i = 2, check 2 <= 5 (true), print 2, then i becomes 3
Step 3: i = 3, check 3 <= 5 (true), print 3, then i becomes 4
Step 4: i = 4, check 4 <= 5 (true), print 4, then i becomes 5
Step 5: i = 5, check 5 <= 5 (true), print 5, then i becomes 6
Step 6: i = 6, check 6 <= 5 (false), STOP

Counting Backwards

for (let i = 5; i >= 1; i--) {
  console.log(i);
}

// Output:
// 5
// 4
// 3
// 2
// 1

Counting by Different Amounts

// Count by 2s
for (let i = 0; i <= 10; i += 2) {
  console.log(i);
}
// Output: 0, 2, 4, 6, 8, 10

// Count by 5s
for (let i = 0; i <= 50; i += 5) {
  console.log(i);
}
// Output: 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50

---

Part 2: Looping Through Arrays

The most common use of loops is processing arrays:

Using a for Loop with Arrays

const fruits = ["Apple", "Banana", "Orange", "Mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log(`Fruit ${i + 1}: ${fruits[i]}`);
}

// Output:
// Fruit 1: Apple
// Fruit 2: Banana
// Fruit 3: Orange
// Fruit 4: Mango
Important: Use i < array.length (not <=) because arrays are zero-indexed.

Calculating Sum of Array

const numbers = [10, 20, 30, 40, 50];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(`Total: ${sum}`);  // Total: 150

---

Part 3: The for...of Loop (Modern Way)

The for...of loop is a simpler way to loop through arrays when you don't need the index:

const colors = ["red", "green", "blue"];

// Old way (for loop)
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

// New way (for...of)
for (const color of colors) {
  console.log(color);
}

// Both output:
// red
// green
// blue

When to Use for...of

const scores = [85, 92, 78, 90, 88];

// ✅ Use for...of when you just need the values
let total = 0;
for (const score of scores) {
  total += score;
}
console.log(`Average: ${total / scores.length}`);

// ✅ Use regular for when you need the index
for (let i = 0; i < scores.length; i++) {
  console.log(`Score ${i + 1}: ${scores[i]}`);
}

---

Part 4: The while Loop

The while loop continues as long as a condition is true.

Basic while Loop

let count = 1;

while (count <= 5) {
  console.log(count);
  count++;
}

// Output: 1, 2, 3, 4, 5

while Loop Syntax

while (condition) {
  // Code to repeat
  // Don't forget to update the condition!
}
Warning: Always make sure the condition eventually becomes false, or you'll create an infinite loop!

When to Use while vs for

// ✅ Use for when you know the number of iterations
for (let i = 0; i < 10; i++) {
  console.log(i);
}

// ✅ Use while when you don't know how many iterations
let userInput = "";
while (userInput !== "quit") {
  // Keep asking until user types "quit"
  // userInput = prompt("Enter command:");
}

Practical while Loop Example

// Find the first power of 2 greater than 1000
let power = 1;
let exponent = 0;

while (power <= 1000) {
  exponent++;
  power = 2 ** exponent;  // 2 to the power of exponent
}

console.log(`2^${exponent} = ${power}`);  // 2^10 = 1024

---

Part 5: The do...while Loop

The do...while loop is like while, but it always runs at least once.

let count = 1;

do {
  console.log(count);
  count++;
} while (count <= 5);

// Output: 1, 2, 3, 4, 5

Difference from while

// while: Check condition BEFORE running
let x = 10;
while (x < 5) {
  console.log(x);  // Never runs because 10 < 5 is false
  x++;
}

// do...while: Check condition AFTER running
let y = 10;
do {
  console.log(y);  // Runs once, prints 10
  y++;
} while (y < 5);

When to Use do...while

Use it when you want to ensure the code runs at least once:

let password;

do {
  // Ask for password (runs at least once)
  password = "user_input";  // In real code, you'd get actual input
  
  if (password.length < 8) {
    console.log("Password too short! Try again.");
  }
} while (password.length < 8);

console.log("Password accepted!");

---

Part 6: The for...in Loop (For Objects)

The for...in loop is primarily for objects (we'll cover these more later), but here's a preview:

const person = {
  name: "Alice",
  age: 30,
  city: "New York"
};

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

// Output:
// name: Alice
// age: 30
// city: New York
Note: For arrays, use for...of, not for...in.

---

Part 7: Loop Control - break and continue

The break Statement

break immediately exits the loop:
// Find the first number divisible by 7
for (let i = 1; i <= 100; i++) {
  if (i % 7 === 0) {
    console.log(`First number divisible by 7: ${i}`);
    break;  // Exit the loop
  }
}
// Output: First number divisible by 7: 7

The continue Statement

continue skips to the next iteration:
// Print odd numbers only
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    continue;  // Skip even numbers
  }
  console.log(i);
}
// Output: 1, 3, 5, 7, 9

break vs continue

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// With break: Stop completely at 5
console.log("With break:");
for (const num of numbers) {
  if (num === 5) break;
  console.log(num);
}
// Output: 1, 2, 3, 4

// With continue: Skip 5, continue with rest
console.log("With continue:");
for (const num of numbers) {
  if (num === 5) continue;
  console.log(num);
}
// Output: 1, 2, 3, 4, 6, 7, 8, 9, 10

---

Part 8: Nested Loops

You can put loops inside loops:

// 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("---");
}

// 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
// ---

2D Arrays (Matrix)

const matrix[] = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Loop through each row
for (let i = 0; i < matrix.length; i++) {
  // Loop through each column in that row
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(`Position [${i}][${j}]: ${matrix[i][j]}`);
  }
}

---

Part 9: Practical Examples

Example 1: Factorial

function factorial(n) {
  let result = 1;
  
  for (let i = 1; i <= n; i++) {
    result *= i;
  }
  
  return result;
}

console.log(factorial(5));  // 120 (5 × 4 × 3 × 2 × 1)

Example 2: Find All Even Numbers

function findEvens(numbers[]) {
  const evens = [];
  
  for (const num of numbers) {
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
  
  return evens;
}

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(findEvens(nums));  // [2, 4, 6, 8, 10]

Example 3: Count Occurrences

function countOccurrences(arr[], target) {
  let count = 0;
  
  for (const item of arr) {
    if (item === target) {
      count++;
    }
  }
  
  return count;
}

const fruits = ["apple", "banana", "apple", "orange", "apple"];
console.log(countOccurrences(fruits, "apple"));  // 3

Example 4: Reverse a String

function reverseString(str) {
  let reversed = "";
  
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  
  return reversed;
}

console.log(reverseString("hello"));  // "olleh"

---

Practice Exercises

Exercise 1: Sum of Numbers

Write a function that calculates the sum of numbers from 1 to n.

Exercise 2: FizzBuzz

Print numbers 1-100, but:

  • Print "Fizz" for multiples of 3
  • Print "Buzz" for multiples of 5
  • Print "FizzBuzz" for multiples of both

Exercise 3: Find Minimum

Write a function that finds the smallest number in an array.

Exercise 4: Count Vowels

Count how many vowels (a, e, i, o, u) are in a string.

Exercise 5: Palindrome Checker

Check if a string reads the same forwards and backwards.

Exercise 6: Prime Numbers

Find all prime numbers between 1 and 100.

---

Common Mistakes

Mistake 1: Infinite Loop

// ❌ INFINITE LOOP - Never updates i!
let i = 0;
while (i < 10) {
  console.log(i);
  // Forgot: i++
}

// ✅ CORRECT
let i = 0;
while (i < 10) {
  console.log(i);
  i++;
}

Mistake 2: Off-by-One Error

const arr = [1, 2, 3, 4, 5];

// ❌ WRONG - goes out of bounds
for (let i = 0; i <= arr.length; i++) {
  console.log(arr[i]);  // arr[5] is undefined!
}

// ✅ CORRECT
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Mistake 3: Modifying Array While Looping

const numbers = [1, 2, 3, 4, 5];

// ❌ WRONG - Array length changes during loop
for (let i = 0; i < numbers.length; i++) {
  numbers.push(i);  // Array keeps growing!
}

// ✅ CORRECT - Store original length
const originalLength = numbers.length;
for (let i = 0; i < originalLength; i++) {
  // Now it's safe
}

---

Key Concepts Summary

Loop Types

Loop Type Best For Example
for Known iteration count for (let i = 0; i < 10; i++)
for...of Iterating array values for (const item of array)
while Unknown iteration count while (condition)
do...while Run at least once do { } while (condition)
for...in Object properties for (const key in object)

Loop Control

Control What It Does
break Exit loop immediately
continue Skip to next iteration

What You Learned

  • ✅ How to use for loops for counted repetitions
  • ✅ How to use for...of to iterate through arrays
  • ✅ How to use while and do...while loops
  • ✅ How to control loop flow with break and continue
  • ✅ How to nest loops for multi-dimensional problems
  • ✅ How to avoid infinite loops
  • ✅ When to choose each type of loop

What's Next?

In the next lesson, you'll learn about objects - how to store related data together using key-value pairs!