JS Loops

Overview

Loops are a fundamental programming concept in JavaScript that allows you to repeat a set of instructions or code blocks multiple times. They are crucial for performing repetitive tasks, iterating over data structures, and automating processes in your JavaScript programs.


Types of Loops

JavaScript provides several types of loops, each with its own use cases and syntax:

1. for Loop

The for loop is one of the most commonly used loops. It repeats a block of code a specified number of times.

Try yourself
        
            for (let i = 0; i < 5; i++) {
    console.log(i);
}
        
    

2. while Loop

The while loop repeats a block of code as long as a specified condition is true.

Try yourself
        
            let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}
        
    

3. do...while Loop

The do...while loop is similar to the while loop but guarantees that the block of code is executed at least once, even if the condition is initially false.

Try yourself
        
            let i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);

        
    

2. for...inLoop

The for...in loop is used to iterate over the properties of an object.

Try yourself
        
            let person = { name: 'John', age: 30 };
for (var key in person) {
    console.log(key + ': ' + person[key]);
}
        
    

5. for...of Loop

The for...of loop is used to iterate over iterable objects like arrays and strings.

Try yourself
        
            let colors = ['red', 'green', 'blue'];
for (var color of colors) {
    console.log(color);
}
        
    

6. Nested Loops Loop

You can nest loops inside each other to perform more complex tasks, such as iterating through multi-dimensional arrays.

Try yourself
        
            for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        console.log(i + '-' + j);
    }
}
        
    

In this example, a for loop is nested inside another for loop.


Loop Control Statements

JavaScript provides control statements that allow you to modify loop behavior

break
Try yourself
        
            for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        break;
    }
    console.log(i);
}
        
    
continue
Try yourself
        
            for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue;
    }
    console.log(i);
}
        
    

Summary

Loops in JavaScript are essential for automating repetitive tasks, iterating through data collections, and controlling program flow. Each type of loop has its own use cases, and understanding how to use them effectively is crucial for writing efficient JavaScript code.