Summary - Conditionals
- Node.js course
- Beginner
- Lesson 41/116
- 5 min
Combine if, switch and optional chaining to write a day-of-week app.
Day-of-week app
In this summary we will combine if, switch and optional chaining to build a day-of-week application. The app takes a day number and prints the day name; it does not throw on missing data.
The flow is: we read the day field of a config object safely with config?.day; we convert the day number to a name with switch; we catch unknown values with default. This way we handle missing data and multi-case scenarios together, as in a real app.
Practice Print the day name
The config variable holds { day: 2 }. Declare a variable day and assign config?.day to it. Then write a switch (day) block: case 1 prints "Monday", case 2 prints "Tuesday" (each case ends with break), the default prints "Unknown". The output on a single line must be Tuesday.
Starter code
const config = { day: 2 };
// Read day with ?.; print the day name with switchSample solution
const config = { day: 2 };
const day = config?.day;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Unknown");
}Expected output
Tuesday
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the switch case
switch (day) {
____ 1:
console.log("Monday");
break;
default:
console.log("Unknown");
}
switch (day) {
case 1:
console.log("Monday");
break;
default:
console.log("Unknown");
}
Explanation: case labels the value 1; the other options are not valid switch keywords.
2 What does config?.day return when config is null?
const config = null;
config?.day- undefined Correct answer
- throws
- 0
- "Monday"
Explanation: ?. does not throw on null; it returns undefined.
3 Match each piece to its job
| Term | Meaning |
|---|---|
if |
Tests one condition |
switch |
Multi-equality select |
? |
Ternary operator |
?. |
Null-safe access |