If / Else: Making Decisions

If / Else: Making Decisions in JavaScript: Your code is not a straight line; it's a "Choose Your Own Adventure" book.

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

  1. Strict Equality: Forgetting that if (0) is false, but if ("0") is true! Always check your "Truthiness."
  2. Dangling Else: When you have many nested if-statements, it's easy to lose track of which else belongs to which if. Keep your nesting shallow.
  3. Assignment in Condition: Accidely typing if (x = 5) (setting x to 5) instead of if (x === 5) (comparing them). This will always return true and break your logic!

Practice Exercises

  1. The Grade Calculator: Write an if/else chain that takes a score (0-100) and prints a letter grade (A, B, C, D, F).
  2. The Light Switch: Create a variable isLightOn. Use a ternary operator to print "The room is bright" or "The room is dark."
  3. The FizzBuzz Lite: Write a condition that checks if a number is divisible by both 3 and 5.