⚡ Lesson 05 of 30
Control Flow – if, switch
Make decisions in your programs using if/else chains, ternary expressions, and switch statements.
if / else if / else
The fundamental decision-making structure:
const score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B"); // prints this
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
Ternary Operator
A compact inline conditional — perfect for simple true/false assignments:
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"
Logical Short-circuit as Conditional
A common pattern in React and modern JS is using && to conditionally render or execute:
const isLoggedIn = true;
isLoggedIn && console.log("Welcome back!"); // prints
switch Statement
Use switch when checking one variable against many specific values. Don't forget break!
const day = "Monday";
switch (day) {
case "Monday":
case "Tuesday":
console.log("Early week"); break;
case "Friday":
console.log("TGIF!"); break;
default:
console.log("Midweek");
}
Optional Chaining ?.
Access deeply nested properties without crashing if an intermediate value is null:
const user = { address: { city: "Kuala Lumpur" } };
console.log(user?.address?.city); // "Kuala Lumpur"
console.log(user?.phone?.number); // undefined (no error!)