Now that we can store data and do math, we need to make decisions. This is where your code gets a "brain."
Topic 3: Conditional Statements
Conditional statements allow your code to perform different actions based on different conditions. If a condition is true, one block of code runs; if it's false, another block (or nothing) runs.
1. if / else if / else
The most common way to branch your logic. It checks conditions in order from top to bottom.
2. Comparison Results
Every condition inside the () of an if statement is evaluated to a Boolean (true or false).
3. Ternary Operator (? :)
A shorthand for a simple if/else. It’s great for assigning a value to a variable based on a condition in just one line.
4. Logical Operators in Conditions
You can combine conditions using && (AND) and || (OR) from the previous topic to make complex decisions.
The Code Example
const hour = 14; // 2:00 PM
let greeting;
// 1. Standard If/Else Logic
if (hour < 12) {
greeting = "Good Morning";
} else if (hour < 18) {
greeting = "Good Afternoon"; // This will run because 14 < 18
} else {
greeting = "Good Evening";
}
console.log(greeting);
// 2. Using Logic in Conditions
const age = 20;
const hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive!");
} else {
console.log("Better take the bus.");
}
// 3. The Ternary Operator (The One-Liner)
// Syntax: (condition) ? (value if true) : (value if false)
const status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // Output: "Adult"