Module 18: Decisions and Functions
Conditions
🏠The everyday picture
"If it's raining, take an umbrella; otherwise, wear sunglasses." Every day we choose based on a condition. Programs do the same.
📘What it really is
ifruns code only when a condition istrue;elseruns when it isn't:
const age = 17;
if (age >= 18) {
console.log("You can register.");
} else {
console.log("Please ask a parent to register for you.");
}
else ifchecks more conditions in order. The first true one wins, and the rest are skipped:
if (score >= 80) {
grade = "Distinction";
} else if (score >= 60) {
grade = "Pass";
} else {
grade = "Try again";
}
- Combine conditions with
&&and||(Module 17). -
Truthy and falsy: in a condition,
0,""(empty text),null,undefinedandNaNcount as false; almost everything else counts as true. Soif (name)means "if a name was given". -
The ternary is a one-line
if:const label = isOpen ? "Open" : "Closed";. - The curly braces
{ }mark which lines belong to the condition. Indentation makes it readable.
🖱️Try it
In main.js, write code that takes a number of modules done (0 to 100) and prints which level the learner is on:
modules 1–10 are Level 1, 11–20 Level 2, and anything above 20 "Level 3 or above". Test with 0, 5, 15 and 40.
✅Quick check
In an if / else if / else chain, a value matches two conditions. Which code runs?
Show the answer
Only the first matching one. The rest are skipped.
What does if (email) check?
Show the answer
Whether email has a truthy value, so not empty, null or undefined.
