JavaScript Loops

Loops in JavaScript are used to execute a block of code repeatedly based on a condition. JavaScript provides several types of loops: `for`, `for-in`, `for-of`, and `while`. Each type has its specific use cases and syntax.

1. For Loop

The `for` loop is used when you know in advance how many times you want to execute a block of code. It includes three main parts: initialization, condition, and increment/decrement:


// For loop example
for (let i = 0; i < 5; i++) {
    console.log(i);
}
// Output: 0 1 2 3 4

            

2. For-In Loop

The `for-in` loop iterates over the enumerable properties of an object. It is typically used to loop through object properties:


// For-in loop example
let person = { firstName: "John", lastName: "Doe", age: 30 };

for (let key in person) {
    console.log(key + ": " + person[key]);
}
// Output: firstName: John \n lastName: Doe \n age: 30

            

3. For-Of Loop

The `for-of` loop is used to iterate over iterable objects like arrays, strings, or other collections. It provides a simpler way to loop through elements compared to `for-in`:


// For-of loop example
let numbers = [1, 2, 3, 4, 5];

for (let number of numbers) {
    console.log(number);
}
// Output: 1 2 3 4 5

            

4. While Loop

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


// While loop example
let count = 0;

while (count < 5) {
    console.log(count);
    count++;
}
// Output: 0 1 2 3 4