05

Loops

Chapter 5 • Beginner

35 min

Loops

Loops allow you to execute a block of code multiple times. This is essential for processing data, repeating actions, and automating tasks.

for Loop

The for loop is the most common type of loop in JavaScript:

javascript.js
for (initialization; condition; increment) {
    // code to execute
}

Components of a for Loop

  1. Initialization: Sets up the loop variable (executed once)
  2. Condition: Checks if the loop should continue
  3. Increment: Updates the loop variable after each iteration
  4. Loop Body: The code that runs in each iteration

while Loop

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

javascript.js
while (condition) {
    // code to execute
}

do-while Loop

Similar to while, but executes at least once:

javascript.js
do {
    // code to execute
} while (condition);

Loop Control

break Statement

Exits the loop immediately:

javascript.js
for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break; // Exit the loop when i equals 5
    }
    console.log(i);
}

continue Statement

Skips the rest of the current iteration:

javascript.js
for (let i = 0; i < 10; i++) {
    if (i === 5) {
        continue; // Skip the rest when i equals 5
    }
    console.log(i);
}

for...of Loop (ES6)

Iterates over iterable objects like arrays:

javascript.js
let fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits) {
    console.log(fruit);
}

for...in Loop

Iterates over object properties:

javascript.js
let person = { name: 'John', age: 30, city: 'New York' };
for (let key in person) {
    console.log(key + ': ' + person[key]);
}

Hands-on Examples

Basic for Loop

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

This for loop initializes i to 1, continues while i is less than or equal to 5, and increments i by 1 after each iteration.