Concept Explanation
Your code is not a straight line; it's a "Choose Your Own Adventure" book. if and else statements are the "Forks in the Road." They allow your app to react differently depending on the input.
Syntax or Core Structure
The Conditionals
const hour = new Date().getHours();
if (hour < 12) {
console.log("Good Morning!");
} else if (hour < 18) {
console.log("Good Afternoon!");
} else {
console.log("Good Evening!");
}
Ternary Operator (The Shortcut)
If you just need to pick between two values, use the "Inline" if. It's much cleaner for simple tasks.
const status = (age >= 18) ? "Adult" : "Minor";
Real World Example
A Login System:
if(isPasswordCorrect === true) → Redirect to Dashboard.else→ Show "Invalid Password" error.
Common Mistakes
- Strict Equality: Forgetting that
if (0)is false, butif ("0")is true! Always check your "Truthiness." - Dangling Else: When you have many nested if-statements, it's easy to lose track of which
elsebelongs to whichif. Keep your nesting shallow. - Assignment in Condition: Accidely typing
if (x = 5)(setting x to 5) instead ofif (x === 5)(comparing them). This will always return true and break your logic!
Practice Exercises
- The Grade Calculator: Write an
if/elsechain that takes a score (0-100) and prints a letter grade (A, B, C, D, F). - The Light Switch: Create a variable
isLightOn. Use a ternary operator to print "The room is bright" or "The room is dark." - The FizzBuzz Lite: Write a condition that checks if a number is divisible by both 3 and 5.