JavaScript Notes
Complete guide to the switch statement in JavaScript. Learn switch-case syntax, fall-through behavior, break usage, default clause, and when to choose switch over if-else with practical examples.
The switch statement provides a clean way to execute different code blocks based on the value of a single expression. It's an alternative to long if-else if chains when you're comparing one variable against multiple possible values.
What is a Switch Statement?
A switch statement evaluates an expression and matches its value against multiple case labels. When a match is found, the corresponding code block executes. If no match is found, the optional default block runs.
Syntax
How Switch Works — Step by Step
- The
expressionis evaluated once. - The result is compared with each
casevalue using strict equality (===). - If a match is found, the code after that
caseexecutes. - The
breakstatement exits the switch block. - If no match is found, the
defaultblock executes (if present).
Basic Examples
Example 1: Day of the Week
Wednesday
Example 2: Fruit Color
Banana is yellow.
The Break Statement
The break statement is critical in switch. Without it, execution "falls through" to the next case.
Without Break (Fall-Through Behavior)
Two Three Four Default
All cases after the match execute because there's no break!
With Break (Correct Behavior)
Two
Intentional Fall-Through (Grouped Cases)
Sometimes fall-through is intentional — to group multiple cases that share the same code:
It's the weekend. Time to relax!
Grouped Cases with Different Actions
Month 4 is in Spring
The Default Clause
The default clause handles cases when no case matches. It can be placed anywhere in the switch, but convention places it last.
Unknown traffic signal color: purple
Switch Uses Strict Equality (===)
Switch comparisons use strict equality — no type coercion occurs:
String '1'
Switch with Expressions
The switch expression can be any valid JavaScript expression:
Grade B
This pattern uses switch(true) to evaluate boolean expressions in cases, similar to if-else chains.Practical Programs
Program 1: Simple Calculator
10 * 5 = 50
Program 2: Month Days Counter
Month 2 of 2024 has 29 days.
Program 3: HTTP Status Code Handler
Not Found - Resource doesn't exist
Program 4: Role-Based Access
Access: Content management Can: Create, Read, Update content
Program 5: Direction Commands
Moving north... Position: (0, 1)
Switch vs If-Else: When to Use Which
| Feature | Switch | If-Else |
|---|---|---|
| Best for | Comparing ONE variable to many values | Complex conditions, ranges |
| Comparison type | Strict equality only (===) | Any comparison operator |
| Readability | Better for 4+ equality checks | Better for 2-3 conditions |
| Range checks | Not directly supported | Natural fit |
| Multiple variables | Not ideal | Works well |
| Performance | Potentially faster (jump table) | Sequential evaluation |
Common Mistakes
Mistake 1: Forgetting Break
Apple Banana Cherry
Mistake 2: Using Loose Equality Expectations
No match - types differ!
Mistake 3: Declaring Variables Without Block Scope
Created
Best Practices
- Always include
breakunless fall-through is intentional (and documented). - Always include
defaultto handle unexpected values. - Use block scoping
{}in cases when declaring variables. - Comment intentional fall-throughs for clarity.
- Consider object lookup for simple value mapping instead of switch.
- Keep switch cases focused — extract complex logic into functions.
Friday
Interview Questions
Q1: What comparison does switch use — == or ===?
Answer: Switch uses strict equality (===). There is no type coercion. case "1" will NOT match the number 1.
Q2: What happens if you omit the break statement?
Answer: Without break, execution "falls through" to the next case regardless of whether it matches. All subsequent cases execute until a break or the end of the switch block is reached.
Q3: Can the default case be placed anywhere in a switch?
Answer: Yes, default can be placed anywhere. However, if placed before other cases without a break, fall-through applies. Convention places it last.
Q4: Can you use expressions in case labels?
Answer: Case labels must be constant expressions evaluated at compile time. However, you can use switch(true) and put expressions in case labels: case (x > 5):.
Q5: How is switch different from if-else performance-wise?
Answer: For many cases with equality checks, some engines can optimize switch into a jump table (O(1) lookup) vs sequential if-else checks (O(n)). In practice, the difference is negligible for small numbers of cases.
Q6: Can you use switch with strings?
Answer: Yes, switch works with any type including strings, numbers, booleans. Comparison is always strict equality.
Q7: What is the scope of variables declared inside a switch?
Answer: Variables declared with var are function-scoped. Variables with let/const are block-scoped to the entire switch (not individual cases), which can cause issues. Use {} blocks in cases to create separate scopes.
Q8: When should you use switch(true)?
Answer: switch(true) is useful when you need range comparisons or complex conditions but prefer switch syntax. Each case contains a boolean expression, and the first truthy one executes.
Q9: Can switch handle multiple values for one action without fall-through?
Answer: Grouped cases (stacking case labels without code between them) is the idiomatic way: case "a": case "b": case "c": /* action */ break;
Q10: What are modern alternatives to switch?
Answer: (1) Object/Map lookup for value mapping, (2) Array methods like find() for condition matching, (3) Strategy pattern for complex behaviors, (4) Optional chaining with nullish coalescing for simple defaults.
Q11: Can you use return inside a switch within a function?
Answer: Yes, return exits the function and implicitly exits the switch, making break unnecessary when returning values.
Q12: How do you handle TypeScript's exhaustive checking with switch?
Answer: TypeScript can verify all enum/union cases are handled. Assign the variable to never type in default: if a case is missing, TypeScript shows a compile error. This ensures type safety.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Switch Statement in JavaScript.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, control, flow, switch
Related JavaScript Master Course Topics