Conditionals

Loading concept...

🚦 Program Flow: Conditionals

Making Your Code Smart Enough to Choose


Imagine you’re at a giant crossroads. Every path leads somewhere different. But you’re not lost — you have a magic compass that tells you exactly which way to go based on what’s happening around you.

That’s what conditionals do in JavaScript. They help your code make decisions, just like you do every day.

“Should I wear a jacket? Is it cold outside?”

Your brain checks the weather, then decides. JavaScript does the same thing with conditionals!


🧭 The Big Picture

graph TD A[Start] --> B{Is it raining?} B -->|Yes| C[Take umbrella ☔] B -->|No| D[Enjoy sunshine ☀️] C --> E[Go outside] D --> E

Every decision follows this pattern: Check something → Do something based on the answer.


1️⃣ If-Else Statements

“If This, Then That”

The if-else statement is your most basic decision-maker. Think of it like asking a yes-or-no question.

🍦 The Ice Cream Stand Story

You walk up to an ice cream stand. You want chocolate, but they might be out!

let hasChocolate = true;

if (hasChocolate) {
  console.log("Yay! Chocolate ice cream!");
} else {
  console.log("I'll take vanilla instead.");
}

What’s happening:

  • We check: “Do they have chocolate?”
  • If yes → We get chocolate 🍫
  • If no → We get vanilla 🍨

🎯 Adding More Choices with else if

What if there are MORE options? Use else if to check multiple things!

let weather = "rainy";

if (weather === "sunny") {
  console.log("Let's go to the beach! 🏖️");
} else if (weather === "rainy") {
  console.log("Movie time at home! 🎬");
} else if (weather === "snowy") {
  console.log("Build a snowman! ⛄");
} else {
  console.log("Just stay cozy inside.");
}

Think of it like a ladder — JavaScript climbs down, checking each condition until one is true!


2️⃣ Switch Statement

“The Menu Board”

When you have many specific options to choose from, switch is cleaner than lots of else if.

🍕 The Pizza Order Story

You’re ordering pizza. Each number on the menu means a different pizza!

let choice = 2;

switch (choice) {
  case 1:
    console.log("Pepperoni Pizza! 🍕");
    break;
  case 2:
    console.log("Cheese Pizza! 🧀");
    break;
  case 3:
    console.log("Veggie Pizza! 🥬");
    break;
  default:
    console.log("That's not on the menu!");
}

Key parts:

  • case = Each menu option
  • break = “Stop here, I found my answer!”
  • default = “None of the above matched”

⚠️ Don’t Forget break!

Without break, JavaScript keeps running ALL the cases below! It’s called “fall-through.”

// Without break - OOPS!
switch (day) {
  case "Monday":
    console.log("Start of week");
  case "Tuesday":
    console.log("Still early");
  // Both will print if day is Monday!
}

3️⃣ Guard Clauses

“The Bouncer at the Door”

Guard clauses are like a bouncer checking your ID. If something’s wrong, they stop you early before you enter.

🚪 The Nightclub Story

function enterClub(age, hasID) {
  // Guard clause 1: Check ID first
  if (!hasID) {
    return "Sorry, no ID, no entry!";
  }

  // Guard clause 2: Check age
  if (age < 21) {
    return "Sorry, you're too young!";
  }

  // If we get here, everything is good!
  return "Welcome to the club! 🎉";
}

Why guards are awesome:

  • ✅ Easy to read (checks problems first)
  • ✅ Main code isn’t buried in nested ifs
  • ✅ Exit early = cleaner code

🆚 Without Guard Clauses (Messy!)

function enterClub(age, hasID) {
  if (hasID) {
    if (age >= 21) {
      return "Welcome to the club! 🎉";
    } else {
      return "Sorry, you're too young!";
    }
  } else {
    return "Sorry, no ID, no entry!";
  }
}

See how it’s nested and harder to follow? Guards keep things flat and clear!


4️⃣ Nullish Values Handling

“The Empty Box Problem”

Sometimes a variable might be empty (null or undefined). We need to handle that gracefully!

📦 The Package Story

You ordered a package, but sometimes nothing arrives…

Using ?? (Nullish Coalescing)

let gift = null;
let whatIGot = gift ?? "Nothing arrived 😢";

console.log(whatIGot);
// Output: "Nothing arrived 😢"

The ?? operator says: “If the left side is null or undefined, use the right side instead.”

🆚 Why Not Just Use ||?

let volume = 0;

// With || (wrong!)
let result1 = volume || 50;
// Result: 50 (treats 0 as "empty"!)

// With ?? (correct!)
let result2 = volume ?? 50;
// Result: 0 (0 is a real value!)
Operator Treats as “empty”
|| null, undefined, 0, "", false
?? Only null and undefined

Optional Chaining ?.

What if you’re looking for something inside something that might not exist?

let user = {
  name: "Alex"
  // no address property!
};

// Without ?. - CRASH! 💥
// let city = user.address.city;

// With ?. - Safe! ✅
let city = user.address?.city;
// Result: undefined (no crash!)

The ?. says: “If this thing doesn’t exist, just stop and give me undefined.”


5️⃣ Ternary Operator

“The One-Liner Decision”

The ternary operator is a shortcut for simple if-else. It fits on one line!

🎂 The Birthday Story

let age = 10;
let canVote = age >= 18 ? "Yes!" : "Not yet!";

console.log(canVote);
// Output: "Not yet!"

The pattern:

condition ? valueIfTrue : valueIfFalse

🎨 Real Examples

// Setting a greeting
let hour = 14;
let greeting = hour < 12 ? "Good morning!" : "Good afternoon!";

// Checking login status
let loggedIn = true;
let message = loggedIn ? "Welcome back!" : "Please log in";

// Quick price calculation
let isMember = true;
let price = isMember ? 10 : 15;

⚠️ Don’t Overdo It!

Ternaries are great for simple choices. For complex logic, use regular if-else!

// ❌ Too confusing!
let result = a > b ? (c > d ? "A" : "B") : (e > f ? "C" : "D");

// ✅ Much clearer with if-else
if (a > b) {
  if (c > d) result = "A";
  else result = "B";
} else {
  if (e > f) result = "C";
  else result = "D";
}

🗺️ When to Use What?

graph TD A[Need to make a decision?] --> B{How many options?} B -->|2 options| C{Simple enough?} C -->|Yes| D[Ternary Operator] C -->|No| E[If-Else] B -->|3+ specific values| F[Switch] B -->|Multiple checks| G{Checking for problems first?} G -->|Yes| H[Guard Clauses] G -->|No| E A --> I{Might be null/undefined?} I -->|Yes| J[Nullish Operators]

🌟 Quick Reference

Tool Best For Example
if-else General decisions if (hungry) { eat(); }
switch Many specific values switch (day) {...}
Guard clauses Early exit on problems if (!valid) return;
?? Default for null/undefined name ?? "Guest"
?. Safe property access user?.email
Ternary Quick two-way choice x > 5 ? "big" : "small"

🎉 You Did It!

You now understand how JavaScript makes decisions! Your code can:

  • ✅ Choose between options with if-else
  • ✅ Handle many cases cleanly with switch
  • ✅ Exit early with guard clauses
  • ✅ Handle missing values with nullish operators
  • ✅ Make quick decisions with ternary

Remember: Conditionals are just your code asking questions and acting on the answers. Just like you do every day!

“Every great program is just a bunch of smart decisions.” 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.