Sub topic 2
Choosing a Value with the Conditional Operator
This chapter assumes you can write if/else chains and know the difference between === and ==. It covers the conditional operator, switch, and the core loop statements.
The Conditional Operator
condition ? a : b is an expression, so it produces a value. Use it when both branches compute one value. Use if when the branches perform actions.
const age = 20;
const label = age >= 18 ? "adult" : "minor";
console.log(label); // "adult"A common error is nesting ternaries several levels deep. Once you need more than two outcomes, an if chain or a lookup is easier to read.
Branching on One Value with switch
switch compares one value against each case using strict equality (===). Execution falls through into the next case until it reaches a break or a return. You can stack empty case labels on purpose so that several values share the same code.
function dayType(day) {
switch (day) {
case "Sat":
case "Sun":
return "weekend";
default:
return "weekday";
}
}
console.log(dayType("Sun")); // "weekend"
console.log(dayType("Mon")); // "weekday"while and do...while
while checks its condition before each pass, so the body may never run. do...while checks after each pass, so the body runs at least once.
let attempts = 0;
do {
attempts++;
console.log("attempt", attempts);
} while (attempts < 3);
let n = 10;
while (n < 3) {
console.log("never runs");
}Counting Loops with for
The for loop puts initialization, condition, and update on one line. Use it when you count or need the index.
for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}Off-by-one errors usually come from writing <= where you meant <.
break, continue, and Labels
break exits the nearest loop. continue skips the rest of the current iteration. A label lets break exit an outer loop from inside a nested one.
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) continue;
if (i * j === 2) break outer;
console.log(i, j);
}
}
// 0 0
// 0 2
// 1 0Exercise
What does switch (1) { case "1": console.log("string"); break; default: console.log("other"); } print, and why?
Show answer
It prints "other". switch uses strict equality, and the number 1 is not === the string "1".
Exercise
In the labeled loop example, why is the pair 1 2 never printed?
Show answer
When i is 1 and j is 2, i * j equals 2, so break outer runs before console.log and exits both loops.