Loops & Switch - Exercise 1

A loop in JavaScript is a programming structure that repeats a block of code while its controlling condition allows another iteration. The loop needs progress toward that condition changing, otherwise it can run forever.

let count = 0;
while (count < 3) {
  console.log(count);
  count++;
}

The classic loops are for, while, and do...while. Use for when setup and updates fit together, while when a condition controls an unknown number of repetitions, and do...while when one run is required.

for (let i = 0; i < 2; i++) console.log(i);
let ready = false;
while (ready) console.log('runs only when ready');
do { console.log('runs once'); } while (false);

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 checks its condition before each iteration. If the condition is false initially, the body does not run, so update the values used by the condition inside the loop.

let attempts = 0;
while (attempts < 2) {
  console.log('try', attempts);
  attempts++;
}

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 runs its body before checking the condition, so it always executes at least once. After that first run, it behaves like a while loop and repeats only while the condition remains true.

let value = 5;
do {
  console.log(value); // prints once
  value++;
} while (value < 5);

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 compares one expression with several case values using strict matching. The matching case runs, and break normally prevents execution from falling into the next case.

const role = 'editor';
switch (role) {
  case 'editor': console.log('Can edit'); break;
  case 'viewer': console.log('Read only'); break;
}

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 is the fallback when no case matches the switch expression. It is useful for unexpected or unsupported values and can still be followed by break when more cases are added later.

const format = 'pdf';
switch (format) {
  case 'html': console.log('Web page'); break;
  default: console.log('Unknown format');
}