JavaScript Loops

1. What are Loops?

Loops are used to execute a block of code repeatedly as long as a specified condition is true. They are essential for handling repetitive tasks, traversing data structures (like arrays and objects), and reducing code redundancy.

2. The `for` Loop

The for loop is the most versatile and commonly used loop. It allows you to define the initialization, condition, and increment/decrement in a single line.

Syntax

for (initialization; condition; update) {
    // code block to be executed
}
        

Example

// Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
    console.log("Iteration: " + i);
}
        
Output will appear here...

3. The `while` Loop

The while loop executes a block of code as long as the specified condition evaluates to true. It is useful when the number of iterations is not known beforehand.

Syntax

while (condition) {
    // code block to be executed
}
        

Example

let count = 1;

while (count <= 3) {
    document.write("Count is: " + count);
    count++;
}
        
Output will appear here...

4. The `do...while` Loop

The do...while loop is similar to the while loop, but it guarantees that the code block is executed at least once before checking the condition.

Syntax

do {
    // code block to be executed
} while (condition);
        

Example

let num = 5;

do {
    document.write("Number: " + num);
    num++;
} while (num < 5); // Condition is false, but runs once
        
Output will appear here...

5. The `for...in` Loop

The for...in loop is designed to iterate over the properties (keys) of an object. It can also iterate over array indices, but for...of is preferred for arrays.

Example

const person = {
    name: "Ragini",
    age: 25,
    city: "Delhi"
};

for (let key in person) {
    document.write(key + ": " + person[key]);
}
        
Output will appear here...

6. The `for...of` Loop

The for...of loop was introduced in ES6. It iterates over the values of iterable objects such as Arrays, Strings, Maps, and Sets.

Example

const colors = ["Red", "Green", "Blue"];

for (let color of colors) {
    document.write(color);
}

const message = "Hello";
for (let char of message) {
    document.write(char);
}
        
Output will appear here...

7. Break and Continue

break: Terminates the loop entirely.
continue: Skips the current iteration and proceeds to the next one.

document.write("--- Break Example ---");
for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        document.write("Breaking at 3");
        break; 
    }
    document.write(i);
}

document.write("\n--- Continue Example ---");
for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        document.write("Skipping 3");
        continue; 
    }
    document.write(i);
}
        
Output will appear here...

8. Comparison Table

Loop Type Description Use Case
for Standard loop with counters Known number of iterations
while Loops while condition is true Unknown iterations
do...while Loops at least once Run at least once
for...in Iterates over keys Object properties (Keys)
for...of Iterates over values Iterable values (Arrays)
Best Practice: Use for...of for arrays to get values directly. Use for...in for objects. Avoid for...in for arrays as order is not guaranteed.

Practice Questions

Test your understanding of JavaScript Loops.

Easy

Q1: Print numbers from 1 to 5.

  • Use a for loop.
  • Initialize a counter variable to 1.
  • Set the condition to run as long as the counter is less than or equal to 5.
  • Log each number to the console.
Easy

Q2: Explain the difference between while and do...while loops.

  • Write a small example of a while loop that might never execute.
  • Write a small example of a do...while loop that executes at least once.
  • Explain why their behavior differs.
Medium

Q3: Iterate over an array using for...of.

  • Declare an array: let fruits = ["apple", "banana", "cherry"];
  • Write a for...of loop to iterate through the array.
  • Print each fruit to the console.
Medium

Q4: Use the continue statement.

  • Write a loop that counts from 1 to 5.
  • Inside the loop, check if the current number is 3.
  • If it is 3, use the continue statement to skip it.
  • Log the remaining numbers to the console.
Hard

Q5: Print a right-angled triangle pattern of stars.

  • Use nested for loops.
  • The outer loop should manage the rows (from 1 to 5).
  • The inner loop should add stars depending on the current row number.
  • Log each completed row to the console.

Answer

Code: