Skip to Content
Course content

23: Conditional Statements

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a pull request from a junior developer who was building a checkout system for an e-commerce site. He had written a great piece of logic to apply a 10% discount for first-time buyers. It worked perfectly during his tests. However, when we hit production, we realized that users who had a "VIP" status were suddenly losing their 20% discount because the code stopped checking for VIP status the moment it saw they were also first-time buyers. He had the logic in the right place, but the order and structure of his conditional statements were fighting each other. It was a humbling reminder that in programming, the path the code takes is just as important as the destination.

Diverting the Flow with If/Else

At its core, a conditional statement is just a fork in the road. You're telling JavaScript: "If this specific thing is true, do this; otherwise, do that." We use the if statement to wrap a block of code that should only execute if a condition evaluates to true. If that condition is false, the engine simply skips over that block entirely.

const userBalance = 45;
const itemPrice = 50;

if (userBalance >= itemPrice) {
  console.log("Purchase successful!");
} else {
  console.log("Insufficient funds. Please add more credits.");
}

In the example above, the expression userBalance >= itemPrice is evaluated first. Since 45 is not greater than or equal to 50, the if block is ignored and the else block runs. I usually tell people to think of the else block as your safety net—it's what happens when none of your specific requirements are met.

Stacking Conditions with Else If

Real-world logic is rarely a simple "yes or no." Most of the time, you have a handful of different possibilities. This is where else if comes in. It allows you to chain multiple checks together. The critical thing to remember here—and this is where that junior dev I mentioned tripped up—is that JavaScript executes these in order. Once it finds a condition that is true, it runs that block and exits the entire chain, ignoring everything else below it.

const userRole = 'editor';

if (userRole === 'admin') {
  console.log("Full access: You can edit, delete, and manage users.");
} else if (userRole === 'editor') {
  console.log("Limited access: You can edit and publish posts.");
} else if (userRole === 'viewer') {
  console.log("Read-only access: You can only view posts.");
} else {
  console.log("Guest access: Please log in to see more.");
}

If userRole was 'admin', the first block would run, and JavaScript wouldn't even look at the 'editor' or 'viewer' checks. If you have conditions that overlap, always put the most specific or most restrictive condition at the top of the chain.

The Ternary Shortcut

Sometimes, writing a full if/else block feels like overkill, especially when you're just trying to assign a value to a variable based on a condition. In those cases, I use the ternary operator. It's essentially a one-line if/else statement. The syntax is a bit strange at first—a question mark followed by a colon—but it's incredibly efficient once you get used to it.

const isLoggedIn = true;
const welcomeMessage = isLoggedIn ? "Welcome back, user!" : "Please sign in to continue.";

console.log(welcomeMessage);

The logic is: condition ? expressionIfTrue : expressionIfFalse. I love using these for UI state toggles, but a word of caution: don't nest ternaries inside other ternaries. It makes the code nearly impossible to read, and your future self (or your teammates) will definitely hate you for it.




📋 Practical Task

Build a Dynamic Subscription-Based Feature Gate

You are building a feature-gate system for a SaaS application. Your goal is to determine what level of access a user has based on their subscription tier and whether their account is currently active.

  • Create a variable subscriptionTier (set it to either 'free', 'pro', or 'enterprise').
  • Create a boolean variable isActive (set it to true or false).
  • Write a conditional structure that logs the following messages to the console:
    • If isActive is false, log: "Account deactivated. Please contact support." (This should take priority over any tier check).
    • If isActive is true AND the tier is 'enterprise', log: "Welcome, Enterprise user! You have unlimited access and a dedicated account manager."
    • If isActive is true AND the tier is 'pro', log: "Welcome, Pro user! You have access to all premium features."
    • If isActive is true AND the tier is 'free', log: "Welcome, Free user! Upgrade to Pro for more features."
    • For any other case (e.g., an unrecognized tier), log: "Invalid account status."

Test your code by changing the values of subscriptionTier and isActive to ensure every path works correctly.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.