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

I'm currently working on a small e-commerce prototype, and I've hit a point where I need to handle different payment methods. Right now, I'm using a chain of if and else if statements. It works, but it's starting to feel clunky.

The if-else sprawl

const paymentMethod = 'paypal';

if (paymentMethod === 'credit_card') {
  console.log('Redirecting to Stripe...');
} else if (paymentMethod === 'paypal') {
  console.log('Redirecting to PayPal login...');
} else if (paymentMethod === 'bitcoin') {
  console.log('Generating wallet address...');
} else if (paymentMethod === 'apple_pay') {
  console.log('Opening Apple Pay sheet...');
} else {
  console.log('Unsupported payment method.');
}

Now, this is perfectly valid JavaScript. But honestly, it's a bit of a mess to read. Every single line repeats paymentMethod ===. When I have four or five options, it's fine. When I have twenty? It becomes a nightmare to maintain. I want something that says, "Look at this one variable, and then find the matching case."

Switching gears

This is where the switch statement comes in. I'm going to rewrite that exact same logic, but instead of asking "is this true?" over and over, I'll just pass the variable into the switch block once.

const paymentMethod = 'paypal';

switch (paymentMethod) {
  case 'credit_card':
    console.log('Redirecting to Stripe...');
    break;
  case 'paypal':
    console.log('Redirecting to PayPal login...');
    break;
  case 'bitcoin':
    console.log('Generating wallet address...');
    break;
  case 'apple_pay':
    console.log('Opening Apple Pay sheet...');
    break;
  default:
    console.log('Unsupported payment method.');
}

It feels much cleaner, right? The switch takes the expression (our variable), and the case keywords act like labels. If the variable matches the label, the code below that label runs.

The danger of the fall-through

I'll be honest: I've made this mistake a hundred times early in my career. Let's see what happens if I forget one of those break statements. I'll remove the break from the paypal case and run it again.

const paymentMethod = 'paypal';

switch (paymentMethod) {
  case 'credit_card':
    console.log('Redirecting to Stripe...');
    break;
  case 'paypal':
    console.log('Redirecting to PayPal login...');
    // I forgot the break here!
  case 'bitcoin':
    console.log('Generating wallet address...');
    break;
  default:
    console.log('Unsupported payment method.');
}

If I run this, the console prints:
"Redirecting to PayPal login..."
"Generating wallet address..."

Wait, why did it do both? This is called "fall-through." In JavaScript, once the engine finds a matching case, it executes every line of code it finds until it hits a break or the end of the switch block. It doesn't care if the subsequent case labels match; it just keeps sliding down. Usually, this is a bug, but occasionally, you can use it to your advantage if you want multiple cases to trigger the same piece of code.

Handling the outliers

Finally, notice that default block at the bottom. I treat that as my safety net. If the user provides a payment method I haven't accounted for—like 'venmo'—the switch will fail all the case checks and land in the default. It's essentially the else at the end of an if-chain. Without it, the switch would just finish without doing anything, which often leaves your user wondering why the app stopped responding.




📋 Practical Task

Build a Subscription Tier Permission Checker

Imagine you are building a streaming service. You need to create a system that checks a user's subscription tier and tells them what features they can access.

Create a variable called userTier and assign it one of the following values: 'free', 'basic', 'premium', or 'admin'.

  • Use a switch statement to check the value of userTier.
  • If 'free': Log "Access limited to ad-supported content."
  • If 'basic': Log "Access to standard definition content."
  • If 'premium': Log "Access to 4K Ultra HD and offline downloads."
  • If 'admin': Log "Full system access: Management Dashboard enabled."
  • Use a default case to handle any unexpected tier values by logging "Invalid subscription tier. Please contact support."

Challenge: Make sure you include break statements for every case so the user doesn't accidentally get admin privileges just because they signed up for a free account!

Rating
0 0

There are no comments for now.

to be the first to leave a comment.