Loops & Switch - Exercise 4
The do...while loop in JavaScript is used to execute a block of code at least once, and then repeat the loop as long as a specified condition is true. The syntax is:
do {
// Code block to be executed
} while (condition);
You can use a do...while loop in JavaScript to execute a block of code at least once and then repeat the loop as long as a specified condition is true.
let i = 0;
do {
console.log(i);
i++;
} while (i < 3);
A labeled loop gives an outer loop a name so break or continue can target it from inside a nested loop. Use labels sparingly because clear helper functions are often easier to maintain.
rows:
for (let row = 0; row < 3; row++) {
for (let column = 0; column < 3; column++) {
if (row === 1) continue rows;
}
}
You can use a labeled loop in JavaScript by providing a label before the loop statement, and then using 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);
}
}
The typeof operator returns a string describing the runtime type of a value. It is useful for simple checks, but remember that typeof null is the historical value "object", and arrays also report "object".
const value = 42;
console.log(typeof value); // "number"
console.log(typeof null); // "object"
Place typeof before a value or
expression. The result is a string such as
"number", "string", or
"boolean".
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
A switch compares one expression with several fixed values and runs the matching case. Because matching is strict, a numeric case such as 1 does not match the string "1".
const level = 2;
switch (level) {
case 1: console.log('Beginner'); break;
case 2: console.log('Intermediate'); break;
}
Use a switch statement when one value needs to be checked against several fixed cases.
const day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
}
A for loop keeps its counter setup, condition, and update in one place. A while loop is a better fit when an external condition controls repetition, but its body must still update that condition to avoid an infinite loop.
for (let index = 0; index < 2; index++) console.log(index);
let pending = 2;
while (pending > 0) pending--;
Fall-through means a matching case continues into the next case when no break is present. It can group several inputs that share behavior, but accidental fall-through often causes bugs, so make the grouping obvious.
const role = 'admin';
switch (role) {
case 'admin':
case 'editor':
console.log('Can edit');
break;
default: console.log('Read only');
}