JavaScript Loops - Exercise 2

In JavaScript, a for loop is typically used when you know the number of iterations beforehand, while a while loop is used when you want to repeat a block of code until a condition is no longer true.

An infinite loop in JavaScript is a loop that continues to execute indefinitely because the condition controlling the loop never evaluates to false.

javascript

while (true) {
    console.log("This is an infinite loop!");
}

The break statement in a loop is used to exit the loop prematurely based on a certain condition, regardless of whether the loop condition is true or false.

The continue statement in a loop is used to skip the rest of the current iteration and continue to the next iteration of the loop.

javascript

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

A labeled statement in JavaScript consists of an identifier followed by a colon (:), which can be used to label a loop or block of code.

You can use a labeled statement in JavaScript to provide a label for a block of code or loop, and then use the label with break or continue statements to control the flow of execution.

javascript

outerloop:
for (let i = 0; i < 3; i++) {
    innerloop:
    for (let j = 0; j < 3; j++) {
        if (i === 1 && j === 1) {
            break outerloop;
        }
        console.log(i, j);
    }
}

A nested loop in JavaScript is used when you want to perform a repetitive task within another repetitive task. It allows you to iterate over each item of one loop for every iteration of another loop.

You can use nested loops in JavaScript by placing one loop inside another loop. This allows you to perform iterations within iterations, executing the inner loop's block of code for each iteration of the outer loop.

javascript

for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        console.log(i, j);
    }
}

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 day = 2;
switch (day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    default:
        console.log("Other day");
}