JavaScript Loops - Exercise 1

A loop in JavaScript is a programming structure that repeats a block of code multiple times until a specified condition is met.

In JavaScript, there are mainly three types of loops: for loop, while loop, and do...while loop.

You can use a for loop in JavaScript to iterate over a block of code a specified number of times, based on initialization, condition, and iteration expression.

javascript

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

A while loop in JavaScript repeats a block of code while a specified condition is true.

You can use a while loop in JavaScript to execute a block of code repeatedly as long as a specified condition is true.

javascript

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

A do...while loop in JavaScript is similar to a while loop, except that it always executes the block of code at least once, and then repeats the loop while a specified condition is true.

You can use a do...while loop in JavaScript to execute a block of code once, and then repeat the loop as long as a specified condition is true.

javascript

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

A switch statement in JavaScript is used to perform different actions based on different conditions.

You can use a switch statement in JavaScript to evaluate an expression and execute a corresponding case block based on the value of the expression.

javascript

let color = "red";
switch (color) {
    case "red":
        console.log("Red color");
        break;
    case "blue":
        console.log("Blue color");
        break;
    default:
        console.log("Other color");
}

The default case in a switch statement is executed when none of the other cases match the expression being evaluated.