Menu

HTML & JS Topic

JavaScript Loops

Why We Need Loops

Without Loops (Tedious!):

javascript

console.log("Count: 1");
console.log("Count: 2");
console.log("Count: 3");
console.log("Count: 4");
console.log("Count: 5");

// Repeated code for each item in array
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

With Loops (Efficient!):

javascript

// Count 1-5
for (let i = 1; i <= 5; i++) {
    console.log("Count:", i);
}

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

The for Loop

Basic Syntax:

javascript

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

Simple Counting Examples:

javascript

// Count up from 1 to 5
for (let i = 1; i <= 5; i++) {
    console.log("Number:", i);
}
// Output: 1, 2, 3, 4, 5

// Count down from 5 to 1
for (let i = 5; i >= 1; i--) {
    console.log("Countdown:", i);
}
// Output: 5, 4, 3, 2, 1

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

// Count by 3s
for (let i = 3; i <= 15; i += 3) {
    console.log("Multiple of 3:", i);
}
// Output: 3, 6, 9, 12, 15

Array Iteration:

javascript

let colors = ["red", "green", "blue", "yellow"];

// Forward iteration
for (let i = 0; i < colors.length; i++) {
    console.log(`Color ${i}: ${colors[i]}`);
}
// Output: Color 0: red, Color 1: green, etc.

// Reverse iteration
for (let i = colors.length - 1; i >= 0; i--) {
    console.log(`Reverse ${i}: ${colors[i]}`);
}
// Output: Reverse 3: yellow, Reverse 2: blue, etc.

// Iterate every other element
for (let i = 0; i < colors.length; i += 2) {
    console.log(`Every other: ${colors[i]}`);
}
// Output: Every other: red, Every other: blue

Nested for Loops:

javascript

// Multiplication table
console.log("Multiplication Table:");
for (let i = 1; i <= 5; i++) {
    for (let j = 1; j <= 5; j++) {
        console.log(`${i} × ${j} = ${i * j}`);
    }
}

// Pattern printing
for (let i = 1; i <= 5; i++) {
    let line = "";
    for (let j = 1; j <= i; j++) {
        line += "* ";
    }
    console.log(line);
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *

// 2D array iteration
let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

for (let row = 0; row < matrix.length; row++) {
    for (let col = 0; col < matrix[row].length; col++) {
        console.log(`matrix[${row}][${col}] = ${matrix[row][col]}`);
    }
}

Advanced for Loop Examples:

javascript

// Multiple initialization/update
for (let i = 0, j = 10; i < j; i++, j--) {
    console.log(`i: ${i}, j: ${j}, sum: ${i + j}`);
}
// Output: i: 0, j: 10, sum: 10
//         i: 1, j: 9, sum: 10
//         ... etc

// Using variables in condition
const MAX = 10;
for (let i = 0; i < MAX; i++) {
    console.log(i);
}

// Loop without initialization (if already initialized)
let k = 5;
for (; k < 10; k++) {
    console.log(k);
}

The while Loop

Basic Syntax:

javascript

while (condition) {
    // code to repeat
}

Simple Examples:

javascript

// Count 1-5
let count = 1;
while (count <= 5) {
    console.log("While count:", count);
    count++; // Don't forget to update!
}
// Output: 1, 2, 3, 4, 5

// User input simulation
let userInput = "";
let attempts = 0;
const PASSWORD = "secret123";

while (userInput !== PASSWORD && attempts < 3) {
    // Simulate getting user input
    userInput = promptSimulate("Enter password:");
    attempts++;
    console.log(`Attempt ${attempts}: ${userInput === PASSWORD ? "Success!" : "Wrong!"}`);
}

function promptSimulate(message) {
    // Simulated prompt - in real browser use actual prompt()
    return attempts === 2 ? "secret123" : "wrong";
}

Game/Simulation Examples:

javascript

// Game health system
let health = 100;
let damagePerHit = 15;

console.log("Battle begins! Health:", health);
while (health > 0) {
    console.log(`⚔️ Enemy attacks!`);
    health -= damagePerHit;
    console.log(`Health remaining: ${health}`);
    
    if (health <= 0) {
        console.log("💀 Game Over!");
        break;
    }
}

// Random number guessing
let targetNumber = Math.floor(Math.random() * 10) + 1;
let guess = 0;
let attempts = 0;

console.log("Guess the number (1-10)");
while (guess !== targetNumber) {
    guess = Math.floor(Math.random() * 10) + 1; // Simulated guess
    attempts++;
    console.log(`Attempt ${attempts}: Guessed ${guess}`);
}
console.log(`🎉 Correct! Took ${attempts} attempts. Number was ${targetNumber}`);

Infinite Loop Prevention:

javascript

// DANGER: Infinite loop
// let x = 0;
// while (x < 5) {  // x never changes!
//     console.log("Stuck forever!");
// }

// Correct: Always update the condition variable
let x = 0;
while (x < 5) {
    console.log("Safe iteration:", x);
    x++; // This prevents infinite loop
}

The do...while Loop

Basic Syntax:

javascript

do {
    // code to execute at least once
} while (condition);

Key Difference: Always runs at least once!

javascript

// Example 1: Runs once even if condition is false initially
let i = 10;
do {
    console.log("do...while:", i);
    i++;
} while (i < 5); // Condition false immediately
// Output: do...while: 10 (runs once!)

// Compare with while loop
let j = 10;
while (j < 5) { // Condition false, so never runs
    console.log("while:", j);
    j++;
}
// No output

// Example 2: Menu system
let choice;
do {
    console.log("\n=== Menu ===");
    console.log("1. View Profile");
    console.log("2. Edit Settings");
    console.log("3. Logout");
    console.log("0. Exit");
    
    // Simulate user choice
    choice = Math.floor(Math.random() * 4); // 0-3
    
    switch(choice) {
        case 1: console.log("Viewing profile..."); break;
        case 2: console.log("Editing settings..."); break;
        case 3: console.log("Logging out..."); break;
        case 0: console.log("Exiting..."); break;
        default: console.log("Invalid choice");
    }
} while (choice !== 0);

Practical Use Cases:

javascript

// Input validation (at least one attempt)
let userAge;
do {
    // Simulate getting age input
    userAge = Math.floor(Math.random() * 30); // Random age 0-29
    console.log(`Entered age: ${userAge}`);
} while (userAge < 18); // Keep asking if under 18

console.log(`Welcome! Age ${userAge} is valid.`);

// Game with replay option
let playAgain;
do {
    console.log("🎮 Starting game...");
    // Game logic here
    console.log("Game over!");
    
    // Simulate asking to play again
    playAgain = Math.random() > 0.5; // Random true/false
    console.log(playAgain ? "Playing again!" : "Thanks for playing!");
} while (playAgain);

Loop Control: break and continue

break Statement - Exit Loop Immediately:

javascript

// Find first even number
for (let i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        console.log(`First even number found: ${i}`);
        break; // Exit loop immediately
    }
    console.log(`Checking ${i}...`);
}
// Output: Checking 1... First even number found: 2

// Search in array
let fruits = ["apple", "banana", "cherry", "date", "elderberry"];
let searchFor = "cherry";

for (let i = 0; i < fruits.length; i++) {
    console.log(`Checking: ${fruits[i]}`);
    if (fruits[i] === searchFor) {
        console.log(`Found at position ${i}`);
        break;
    }
}

// Break in nested loops
outerLoop: // Label (optional but useful for nested loops)
for (let i = 1; i <= 3; i++) {
    console.log(`Outer loop: ${i}`);
    
    for (let j = 1; j <= 3; j++) {
        console.log(`  Inner loop: ${j}`);
        
        if (i === 2 && j === 2) {
            console.log("Breaking both loops!");
            break outerLoop; // Break outer loop from inner
        }
    }
}

continue Statement - Skip Current Iteration:

javascript

// Skip odd numbers
for (let i = 1; i <= 10; i++) {
    if (i % 2 !== 0) {
        continue; // Skip to next iteration
    }
    console.log(`Even number: ${i}`);
}
// Output: Even number: 2, 4, 6, 8, 10

// Process only valid items
let data = [5, -2, 10, null, 8, undefined, 15, "text", 20];

for (let i = 0; i < data.length; i++) {
    // Skip non-numbers and negative numbers
    if (typeof data[i] !== "number" || data[i] < 0) {
        console.log(`Skipping invalid: ${data[i]}`);
        continue;
    }
    
    console.log(`Processing valid number: ${data[i]}`);
    let squared = data[i] ** 2;
    console.log(`  Squared: ${squared}`);
}

// Skip processing for certain conditions
let tasks = [
    { name: "Task 1", completed: true },
    { name: "Task 2", completed: false },
    { name: "Task 3", completed: true },
    { name: "Task 4", completed: false }
];

for (let task of tasks) {
    if (task.completed) {
        console.log(`Skipping completed: ${task.name}`);
        continue;
    }
    
    console.log(`Processing: ${task.name}`);
    // Process incomplete tasks
}

Practical Examples with Control Statements:

javascript

// Shopping cart with break
let cart = ["apple", "banana", "milk", "eggs", "bread"];
let budget = 20;
let prices = { apple: 2, banana: 1, milk: 3, eggs: 4, bread: 2 };
let total = 0;

console.log("Processing items...");
for (let item of cart) {
    let price = prices[item];
    
    if (total + price > budget) {
        console.log(`⚠️ Cannot add ${item}. Budget exceeded!`);
        break;
    }
    
    total += price;
    console.log(`Added ${item} for $${price}. Total: $${total}`);
}
console.log(`Final total: $${total}`);

// Data filtering with continue
let students = [
    { name: "Alice", grade: 85, present: true },
    { name: "Bob", grade: 92, present: true },
    { name: "Charlie", grade: 78, present: false },
    { name: "Diana", grade: 95, present: true },
    { name: "Eve", grade: 88, present: false }
];

console.log("Processing student records...");
for (let student of students) {
    // Skip absent students
    if (!student.present) {
        console.log(`Skipping ${student.name} (absent)`);
        continue;
    }
    
    // Skip low grades
    if (student.grade < 80) {
        console.log(`Skipping ${student.name} (low grade: ${student.grade})`);
        continue;
    }
    
    // Process only present students with good grades
    console.log(` ${student.name}: ${student.grade}% - Eligible for award`);
}

Modern Looping Alternatives

for...of Loop (for arrays, strings):

javascript

// Iterate arrays
let colors = ["red", "green", "blue"];
for (let color of colors) {
    console.log(color); // Direct value, no index needed
}

// Iterate strings
let text = "Hello";
for (let char of text) {
    console.log(char); // H, e, l, l, o
}

// With index (using entries)
for (let [index, color] of colors.entries()) {
    console.log(`${index}: ${color}`);
}

for...in Loop (for object properties):

javascript

let person = {
    name: "John",
    age: 30,
    city: "New York"
};

for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}
// Output: name: John, age: 30, city: New York

// Be careful: includes inherited properties
Array.prototype.customMethod = function() {};
let arr = [1, 2, 3];
for (let index in arr) {
    console.log(index); // 0, 1, 2, "customMethod" (unexpected!)
}

Array Methods (Modern alternative to loops):

javascript

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

// forEach - iterate
numbers.forEach(num => console.log(num));

// map - transform
let doubled = numbers.map(num => num * 2);

// filter - select
let evens = numbers.filter(num => num % 2 === 0);

// reduce - accumulate
let sum = numbers.reduce((total, num) => total + num, 0);

Complete Practical Examples

Example 1: Temperature Converter

javascript

console.log("=== Temperature Conversion Table ===");
console.log("Celsius\t\tFahrenheit");
console.log("----------------------");

for (let celsius = -10; celsius <= 30; celsius += 5) {
    let fahrenheit = (celsius * 9/5) + 32;
    console.log(`${celsius}°C\t\t${fahrenheit.toFixed(1)}°F`);
}

// Alternative with while
console.log("\n=== Reverse Conversion ===");
let fahr = 32;
while (fahr <= 100) {
    let celsius = (fahr - 32) * 5/9;
    console.log(`${fahr}°F = ${celsius.toFixed(1)}°C`);
    fahr += 10;
}

Example 2: Number Guessing Game

javascript

function numberGuessingGame() {
    const MIN = 1;
    const MAX = 100;
    const target = Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;
    let attempts = 0;
    let guess;
    const MAX_ATTEMPTS = 10;
    
    console.log("🎯 Number Guessing Game!");
    console.log(`I'm thinking of a number between ${MIN} and ${MAX}`);
    console.log(`You have ${MAX_ATTEMPTS} attempts.`);
    
    while (attempts < MAX_ATTEMPTS) {
        // Simulate user guess (in real app, use prompt())
        guess = Math.floor(Math.random() * 100) + 1;
        attempts++;
        
        console.log(`\nAttempt ${attempts}: You guessed ${guess}`);
        
        if (guess < target) {
            console.log("📈 Too low! Try higher.");
        } else if (guess > target) {
            console.log("📉 Too high! Try lower.");
        } else {
            console.log(`🎉 Congratulations! You found it in ${attempts} attempts!`);
            break;
        }
        
        if (attempts === MAX_ATTEMPTS) {
            console.log(`💀 Game over! The number was ${target}`);
        }
    }
}

numberGuessingGame();

Example 3: Data Processing Pipeline

javascript

// Process student scores
let students = [
    { name: "Alice", scores: [85, 92, 88] },
    { name: "Bob", scores: [78, 81, 74] },
    { name: "Charlie", scores: [92, 95, 89] },
    { name: "Diana", scores: [65, 70, 68] }
];

console.log("=== Student Grade Report ===\n");

for (let student of students) {
    console.log(`📚 ${student.name}:`);
    let total = 0;
    let hasFailed = false;
    
    // Process individual scores
    for (let i = 0; i < student.scores.length; i++) {
        let score = student.scores[i];
        
        // Skip calculation if any score is below 40
        if (score < 40) {
            console.log(`   Test ${i+1}: ${score} (FAILED)`);
            hasFailed = true;
            continue;
        }
        
        total += score;
        console.log(`   Test ${i+1}: ${score}`);
    }
    
    if (hasFailed) {
        console.log(`   Overall: FAILED - Score below 40`);
        continue; // Skip to next student
    }
    
    let average = total / student.scores.length;
    let grade = average >= 80 ? "A" : 
                average >= 70 ? "B" : 
                average >= 60 ? "C" : "D";
    
    console.log(`   Average: ${average.toFixed(1)}`);
    console.log(`  Grade: ${grade}\n`);
}

Performance Considerations

Loop Optimization:

javascript

// ❌ Bad: Recalculating length each iteration
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {  // arr.length called each time
    // ...
}

// ✅ Good: Cache length
for (let i = 0, len = arr.length; i < len; i++) {
    // arr.length only called once
}

//  Bad: Nested loops with same operation
for (let i = 0; i < 1000; i++) {
    for (let j = 0; j < 1000; j++) {
        console.log(i, j); // Expensive in loop
    }
}

// Better: Minimize work inside loops
for (let i = 0; i < 1000; i++) {
    let innerResult = "";
    for (let j = 0; j < 1000; j++) {
        innerResult += `${i},${j} `;
    }
    console.log(innerResult); // Single console.log
}

Quick Reference

Loop Types:

javascript

// for loop
for (let i = 0; i < 10; i++) { }

// while loop
while (condition) { }

// do...while loop
do { } while (condition);

// for...of (arrays, strings)
for (let item of array) { }

// for...in (object properties)
for (let key in object) { }

Control Statements:

javascript

break;          // Exit loop immediately
continue;       // Skip to next iteration
break label;    // Break specific nested loop

Common Patterns:

javascript

// Count 1-10
for (let i = 1; i <= 10; i++) { }

// Iterate array
for (let i = 0; i < arr.length; i++) { }

// Reverse array
for (let i = arr.length - 1; i >= 0; i--) { }

// Find element (with break)
for (let item of arr) {
    if (item === target) {
        // Found
        break;
    }
}

// Skip elements (with continue)
for (let item of arr) {
    if (shouldSkip(item)) {
        continue;
    }
    // Process item
}

Common Mistakes to Avoid

javascript

// 1. Infinite loops
// let i = 0;
// while (i < 5) { }  // i never increments

// 2. Off-by-one errors
let arr = [1, 2, 3];
// for (let i = 0; i <= arr.length; i++) { }  // <= causes out of bounds
for (let i = 0; i < arr.length; i++) { }  // Correct

// 3. Modifying array while iterating
let numbers = [1, 2, 3, 4, 5];
// for (let i = 0; i < numbers.length; i++) {
//     numbers.splice(i, 1);  // Changes indices during loop
// }

// 4. Using for...in on arrays
let colors = ["red", "green", "blue"];
// for (let index in colors) {
//     console.log(index);  // Works but not recommended
// }
// Use for...of instead
for (let color of colors) {
    console.log(color);
}

// 5. Not initializing loop variables
// for (i = 0; i < 5; i++) { }  // i becomes global!
for (let i = 0; i < 5; i++) { }  // i is block-scoped

Practice these loops by creating your own examples and experimenting in the browser console!

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?