JavaScript Loops

Repeating code execution with for, while, and other loop types

🔄 What are JavaScript Loops?

Loops allow you to repeat code multiple times. Instead of writing the same code over and over, you can use loops to execute code blocks repeatedly.


// Basic for loop example
for (let i = 1; i <= 3; i++) {
    console.log("Count: " + i);
}
                                    

Output:

Count: 1

Count: 2

Count: 3

Types of Loops

for

For Loop

Loop with counter variable

for (init; condition; update) {
  // code
}
while

While Loop

Loop while condition is true

while (condition) {
  // code
}
do

Do While

Execute at least once

do {
  // code
} while (condition);
for...of

For Of

Loop through array values

for (let item of array) {
  // code
}

🔹 For Loop

The most common loop type, perfect when you know how many times to repeat:

// Basic for loop
for (let i = 0; i < 5; i++) {
    console.log("Iteration " + i);
}

// Counting backwards
for (let i = 5; i > 0; i--) {
    console.log("Countdown: " + i);
}

// Skip numbers (increment by 2)
for (let i = 0; i <= 10; i += 2) {
    console.log("Even number: " + i);
}

Output:

Iteration 0, Iteration 1, Iteration 2, Iteration 3, Iteration 4

Countdown: 5, Countdown: 4, Countdown: 3, Countdown: 2, Countdown: 1

Even number: 0, Even number: 2, Even number: 4, Even number: 6, Even number: 8, Even number: 10

🔹 While Loop

Repeats while a condition is true - be careful to avoid infinite loops:

// Basic while loop
let count = 0;
while (count < 3) {
    console.log("Count is: " + count);
    count++; // Important: update the counter!
}

// User input simulation
let password = "";
let attempts = 0;
while (password !== "secret" && attempts < 3) {
    password = "secret"; // Simulating user input
    attempts++;
    console.log("Attempt " + attempts);
}

if (password === "secret") {
    console.log("Access granted!");
} else {
    console.log("Too many attempts!");
}

Output:

Count is: 0

Count is: 1

Count is: 2

Attempt 1

Access granted!

🔹 Do While Loop

Executes the code block at least once, then repeats while condition is true:

// Basic do while
let number = 0;
do {
    console.log("Number is: " + number);
    number++;
} while (number < 3);

// Menu system example
let choice;
do {
    console.log("Menu: 1-Start, 2-Settings, 3-Exit");
    choice = 3; // Simulating user choice
    
    switch (choice) {
        case 1:
            console.log("Starting game...");
            break;
        case 2:
            console.log("Opening settings...");
            break;
        case 3:
            console.log("Goodbye!");
            break;
        default:
            console.log("Invalid choice!");
    }
} while (choice !== 3);

Output:

Number is: 0

Number is: 1

Number is: 2

Menu: 1-Start, 2-Settings, 3-Exit

Goodbye!

🔹 For...Of Loop

Perfect for looping through arrays and other iterable objects:

// Loop through array
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
    console.log("I like " + fruit);
}

// Loop through string
let word = "hello";
for (let letter of word) {
    console.log("Letter: " + letter);
}

// With array of numbers
let numbers = [10, 20, 30, 40];
let sum = 0;
for (let num of numbers) {
    sum += num;
}
console.log("Total sum: " + sum);

Output:

I like apple

I like banana

I like orange

Letter: h, Letter: e, Letter: l, Letter: l, Letter: o

Total sum: 100

🔹 Break and Continue

Control loop execution with break and continue statements:

// Break - exit the loop
for (let i = 0; i < 10; i++) {
    if (i === 5) {
        console.log("Breaking at " + i);
        break; // Exit the loop
    }
    console.log("Number: " + i);
}

// Continue - skip current iteration
for (let i = 0; i < 5; i++) {
    if (i === 2) {
        console.log("Skipping " + i);
        continue; // Skip to next iteration
    }
    console.log("Processing: " + i);
}

// Finding first even number
let numbers = [1, 3, 7, 8, 9, 12];
for (let num of numbers) {
    if (num % 2 === 0) {
        console.log("First even number: " + num);
        break;
    }
}

Output:

Number: 0, Number: 1, Number: 2, Number: 3, Number: 4

Breaking at 5

Processing: 0, Processing: 1, Skipping 2, Processing: 3, Processing: 4

First even number: 8

🧠 Test Your Knowledge

Which loop executes at least once, even if the condition is false?