JavaScript Beginner

JavaScript Loops: For, While, and Iteration

CodingerWeb
CodingerWeb
16 views 50 min read

Repeating Code with Loops

Loops allow you to execute code repeatedly. JavaScript provides several types of loops for different situations.

The for Loop

Best for when you know how many times you want to repeat:

// Basic for loop
for (let i = 0; i < 5; i++) {
    console.log(`Count: ${i}`);
}
// Output: Count: 0, Count: 1, Count: 2, Count: 3, Count: 4

// Counting backwards
for (let i = 10; i >= 1; i--) {
    console.log(i);
}
console.log("Blast off!");

The while Loop

Best for when you don't know exactly how many iterations you need:

let count = 0;
while (count < 3) {
    console.log(`While count: ${count}`);
    count++;
}

// Be careful with infinite loops!
let userInput = "";
while (userInput !== "quit") {
    // In real code, you'd get actual user input
    console.log("Type 'quit' to exit");
    break; // This prevents infinite loop in our example
}

The do...while Loop

Executes at least once, then checks the condition:

let number;
do {
    number = Math.floor(Math.random() * 10) + 1;
    console.log(`Generated number: ${number}`);
} while (number !== 7);
console.log("Finally got 7!");

Looping Through Arrays

let fruits = ["apple", "banana", "orange", "grape"];

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

// for...of loop (modern approach)
for (let fruit of fruits) {
    console.log(`I like ${fruit}`);
}

// for...in loop (for indices)
for (let index in fruits) {
    console.log(`Index ${index}: ${fruits[index]}`);
}

Looping Through Objects

let person = {
    name: "Alice",
    age: 30,
    city: "New York",
    job: "Developer"
};

// for...in loop for objects
for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}

// Object.keys() with for...of
for (let key of Object.keys(person)) {
    console.log(`${key}: ${person[key]}`);
}

Loop Control: break and continue

// break - exits the loop completely
for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;  // Stop when i equals 5
    }
    console.log(i);  // Prints 0, 1, 2, 3, 4
}

// continue - skips current iteration
for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue;  // Skip even numbers
    }
    console.log(i);  // Prints 1, 3, 5, 7, 9
}

Nested Loops

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

Practice Exercises

// Exercise 1: Sum of numbers
let sum = 0;
for (let i = 1; i <= 100; i++) {
    sum += i;
}
console.log(`Sum of 1 to 100: ${sum}`);

// Exercise 2: Find even numbers
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evenNumbers = [];

for (let num of numbers) {
    if (num % 2 === 0) {
        evenNumbers.push(num);
    }
}
console.log("Even numbers:", evenNumbers);

// Exercise 3: Reverse a string
let text = "JavaScript";
let reversed = "";

for (let i = text.length - 1; i >= 0; i--) {
    reversed += text[i];
}
console.log(`Original: ${text}`);
console.log(`Reversed: ${reversed}`);

// Exercise 4: Count vowels
let sentence = "Hello World";
let vowels = "aeiouAEIOU";
let vowelCount = 0;

for (let char of sentence) {
    if (vowels.includes(char)) {
        vowelCount++;
    }
}
console.log(`Vowels in "${sentence}": ${vowelCount}`);