JavaScript
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Types
-
Section 3: Strings and Numbers in Depth
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Objects and Arrays
-
Section 7: Maps, Sets, and Symbols
-
Section 8: Asynchronous JavaScript
-
Section 9: Object-Oriented and Prototypes
-
Section 10: The DOM
-
Section 11: Browser APIs
-
Section 12: Modern JavaScript (ES2015-ES2025)
-
Section 13: Functional Programming Patterns
-
Section 14: Error Handling and Debugging
-
Section 15: Testing
-
Section 16: Accessibility for JavaScript Developers
-
Section 17: Internationalization and Localization
-
Section 18: Performance
-
Section 19: Node.js Fundamentals
-
Section 20: Regular Expressions
-
Section 21: Design Patterns in JavaScript
-
Section 22: Security Basics
-
Section 23: Data Structures and Algorithms in JavaScript
-
Section 24: Practical Projects
-
Section 25: More Advanced Async Patterns
-
Section 26: More Object and Class Practice
-
Section 27: Working with Dates and Internationalization
-
Section 28: Web Components
-
Section 29: More DOM and Browser Practice
-
Section 30: Build Tooling for Vanilla JavaScript
-
Section 31: More Practice Projects
-
Section 32: Interview and Algorithm Practice
-
Section 33: Error Objects (MDN Reference)
-
Section 34: TypedArrays and Binary Data
-
Section 35: Reflection and Metaprogramming (MDN Reference)
-
Section 36: More Global Functions (MDN Reference)
25: Switch Statements
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
switchstatement to check the value ofuserTier. - 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
defaultcase 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!
There are no comments for now.