Loops & Switch - Exercise 2
A for loop keeps initialization, condition, and update together, so it suits a known counter range. A while loop is clearer when repetition depends on a condition whose number of iterations is not known in advance.
for (let i = 0; i < 3; i++) console.log(i);
let value = 3;
while (value > 0) value--;
An infinite loop in JavaScript is a loop that continues to execute indefinitely because the condition controlling the loop never evaluates to false.
while (true) {
console.log("This is an infinite loop!");
}
break immediately exits the nearest loop, even if its normal condition would allow more iterations. Put it behind a meaningful condition when a search or early success makes the remaining work unnecessary.
const values = [3, 8, 12, 4];
for (const value of values) {
if (value > 10) { console.log(value); break; }
}
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.
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
console.log(i);
}
A label gives a loop or block a name followed by a colon. Labeled break or continue can then target an outer loop instead of only the nearest one, which is mainly useful for nested loops.
search:
for (let row = 0; row < 3; row++) {
for (let column = 0; column < 3; column++) {
if (row === 1 && column === 2) break search;
}
}
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.
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 runs the inner loop once for every iteration of the outer loop. This is useful for grids, pairs, and comparisons, but the total work grows quickly as both loop sizes increase.
const rows = ['A', 'B'];
const columns = [1, 2];
for (const row of rows) {
for (const column of columns) console.log(row, column);
}
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.
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(i, j);
}
}
A switch selects behavior by comparing one expression with several fixed case values. It can be easier to scan than a long chain of equality checks, and break controls whether later cases run.
const status = 404;
switch (status) {
case 200: console.log('Success'); break;
case 404: console.log('Not found'); break;
default: console.log('Other response');
}
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.
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
}