Course contentsShow
← JavaScript
Lesson 328 of 2,7239. Control FlowFree lesson

Common Switch Pitfalls

Avoid mistakes like missing breaks, using non-primitive expressions, and forgetting default cases.

Common Switch Pitfalls

You'll learn the most frequent mistakes developers make with switch statements and how to avoid them.

Switch statements can be powerful, but they come with traps that can lead to bugs if you're not careful. Let's examine the pitfalls that commonly trip up developers.

Missing Break Statements

The most notorious pitfall is forgetting break statements. Without them, execution "falls through" to subsequent cases unintentionally:

let score = 'B';
let message;

switch (score) {
  case 'A':
    message = 'Excellent';
    // Missing break!
  case 'B':
    message = 'Good';
    // Missing break!
  case 'C':
    message = 'Average';
}

// message is 'Average' (not 'Good')!

Even though score is 'B', the missing breaks cause execution to continue, overwriting your intended result.

Forgetting the Default Case

Without a default clause, your switch can silently do nothing when no cases match:

switch (userInput) {
  case 'yes':
    processYes();
    break;
  case 'no':
    processNo();
    break;
  // No default - unexpected inputs are ignored
}

Always include default to handle unexpected values explicitly.

Using Non-Primitive Expressions

Switch uses strict equality (===), which doesn't work as expected with objects or arrays:

let arr = [1, 2];

switch (arr) {
  case [1, 2]: // This will NEVER match
    console.log('Matched');
    break;
}

Each array literal creates a new reference, so arr === [1, 2] is always false. Stick to primitives (strings, numbers, booleans) in switch statements.

Key Takeaway: Always include breaks unless fall-through is intentional, always add a default case for safety, and only use switch with primitive values.