Control Flow Logic
Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run.
1. if / else if / else
The most common way to branch logic.
const hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
2. Ternary Operator
A clean shorthand for simple if/else assignments.
Syntax: condition ? runIfTrue : runIfFalse
const age = 20;
const allowed = age >= 18 ? "Welcome!" : "Too young";
3. Switch Statement
Used when you are checking the same variable against multiple possible explicit values. It is cleaner than drawing out ten else if blocks.
const role = "admin";
switch (role) {
case "admin":
console.log("Full Access");
break; // Crucial! Without break, logic falls through to the next case.
case "editor":
console.log("Write Access");
break;
default:
console.log("Read-only Access");
}