Loops and Iteration

Learn how to repeat actions efficiently using loops to process collections and automate repetitive tasks.

Why Use Loops?

// Without loops (tedious):
console.log(1);
console.log(2);
console.log(3);
// ... up to 10

// With loops (efficient):
for (let i = 1; i <= 10; i++) {
console.log(i);
}
1
2
3
...
10

Loops automate repetitive tasks, making code shorter, more readable, and easier to maintain.

For Loop

// Count from 0 to 4
for (let i = 0; i < 5; i++) {
console.log("Count: " + i);
}

// Countdown from 5 to 1
for (let count = 5; count > 0; count--) {
console.log(count);
}
Count: 0
Count: 1
...
5
4
3
2
1

Structure: for (initialization; condition; increment)

While Loop

// While condition is true
let counter = 3;
while (counter > 0) {
console.log(counter);
counter--;
}

// Password validation example
let password = "";
while (password !== "secret123") {
password = prompt("Enter password:");
}
3
2
1
(Password prompt until correct)

Use when you don't know how many iterations are needed beforehand.

Do-While Loop

// Runs at least once
let userInput;
do {
userInput = prompt("Enter yes or no:");
} while (userInput !== "yes" && userInput !== "no");
Keeps prompting until valid input

Use when you need to execute the loop body at least once before checking condition.

Looping Through Arrays

// Traditional for loop
const fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

// Modern for...of loop
for (const fruit of fruits) {
console.log(fruit.toUpperCase());
}
apple
banana
orange
APPLE
BANANA
ORANGE

for...of is cleaner for array iteration when index isn't needed.

Break and Continue

// Break: Exit loop early
for (let i = 1; i <= 10; i++) {
if (i === 6) break;
console.log(i);
}

// Continue: Skip current iteration
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
1
2
3
4
5
---
1
2
4
5

break exits the loop completely, continue skips to next iteration.

Nested Loops

// Multiplication table
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} * ${j} = ${i * j}`);
}
}
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
...
3 * 3 = 9

Use nested loops for multi-dimensional data structures or combinatorial operations.

Common Loop Mistakes

// 1. Infinite loops
while (true) { /* ❌ Runs forever */ }
for (let i=0; i<10; i--) { /* ❌ Never ends */ }

// 2. Off-by-one errors
for (let i=0; i <= 5; i++) { /* Runs 6 times */ }

// 3. Modifying array while looping
const numbers = [1,2,3];
for (let i=0; i<numbers.length; i++) {
numbers.pop(); // ❌ Causes unexpected behavior
}

// 4. Using var in loops
for (var i=0; i<5; i++) { /* i leaks out */ }
console.log(i); // 5 (should use let)

Always test edge cases and consider loop termination conditions carefully.

Practical Loop Examples

// 1. Sum array elements
const prices = [4.99, 12.50, 3.75];
let total = 0;
for (const price of prices) {
total += price;
}

// 2. Find maximum value
const scores = [88, 92, 78, 95];
let max = scores[0];
for (let i = 1; i < scores.length; i++) {
if (scores[i] > max) max = scores[i];
}

// 3. Filter array
const numbers = [1,2,3,4,5,6];
const evens = [];
for (const num of numbers) {
if (num % 2 === 0) evens.push(num);
}
total: 21.24
max: 95
evens: [2,4,6]

Interactive Loops

// For loop button
document.getElementById("forLoopBtn").addEventListener("click", () => {
let output = "";
for (let i = 1; i <= 5; i++) {
output += `Iteration ${i}\n`;
}
document.getElementById("output").textContent = output;
});

// Array processing button
document.getElementById("arrayBtn").addEventListener("click", () => {
const products = ["Laptop", "Phone", "Tablet"];
let html = "<ul>";
for (const product of products) {
html += `<li>${product}</li>`;
}
html += "</ul>";
document.getElementById("output").innerHTML = html;
});

Your Task: Number Analyzer

Create JavaScript code that:

  1. Adds click handlers for all four buttons
  2. For each button:
    • For Loop: Generate and display multiplication table (1-5)
    • While Loop: Generate random numbers (1-100) until one > 90, display all attempts
    • Process Array:
      const numbers = [7, 23, 14, 42, 8, 51];
      Display: sum, average, min, max
    • Nested Loops:Create a 4x4 grid of asterisks using nested loops:
      * * * *
      * * * *
      * * * *
      * * * *
  3. Use appropriate loop types for each task
  4. Include at least:
    • One break/continue statement
    • One for...of loop
    • One nested loop

Challenge: For the array processing, also find and display prime numbers

Tip: For min/max, initialize with first array element

Section 1/11Why Use Loops?

Why Use Loops?

Loops automate repetitive tasks, making code shorter, more readable, and easier to maintain.

Loops and Iteration

Learn how to repeat actions efficiently using loops to process collections and automate repetitive tasks.

Why Use Loops?

// Without loops (tedious):
console.log(1);
console.log(2);
console.log(3);
// ... up to 10

// With loops (efficient):
for (let i = 1; i <= 10; i++) {
console.log(i);
}
1
2
3
...
10

Loops automate repetitive tasks, making code shorter, more readable, and easier to maintain.

Preview