0
0
Javascriptprogramming~20 mins

Switch statement in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of switch with fall-through
What is the output of the following code?
Javascript
const value = 2;
switch(value) {
  case 1:
    console.log('One');
  case 2:
    console.log('Two');
  case 3:
    console.log('Three');
    break;
  default:
    console.log('Default');
}
ATwo\nThree
BOne\nTwo\nThree
CThree
DDefault
Attempts:
2 left
💡 Hint
Remember that without break, cases fall through to the next.
Predict Output
intermediate
2:00remaining
Switch with string cases
What will this code print?
Javascript
const fruit = 'apple';
switch(fruit) {
  case 'banana':
    console.log('Banana');
    break;
  case 'apple':
    console.log('Apple');
    break;
  case 'orange':
    console.log('Orange');
    break;
  default:
    console.log('Unknown fruit');
}
ABanana
BUnknown fruit
COrange
DApple
Attempts:
2 left
💡 Hint
Check which case matches the string exactly.
Predict Output
advanced
2:00remaining
Switch with multiple cases and default
What is the output of this code snippet?
Javascript
const num = 5;
switch(num) {
  case 1:
  case 3:
  case 5:
    console.log('Odd');
    break;
  case 2:
  case 4:
    console.log('Even');
    break;
  default:
    console.log('Unknown');
}
AUnknown
BOdd
CEven
DSyntaxError
Attempts:
2 left
💡 Hint
Multiple cases can share the same code block.
Predict Output
advanced
2:00remaining
Switch with expression and type coercion
What will this code print?
Javascript
const val = '2';
switch(val) {
  case 1:
    console.log('Number 1');
    break;
  case 2:
    console.log('Number 2');
    break;
  case '2':
    console.log('String 2');
    break;
  default:
    console.log('Default');
}
AString 2
BNumber 2
CDefault
DNumber 1
Attempts:
2 left
💡 Hint
Switch uses strict equality (===) to compare values.
🧠 Conceptual
expert
2:00remaining
Behavior of switch with no matching case and no default
What happens when a switch statement has no matching case and no default case?
AIt executes the first case by default.
BIt throws a ReferenceError at runtime.
CThe switch block is skipped and no code inside runs.
DIt causes an infinite loop.
Attempts:
2 left
💡 Hint
Think about what happens if no case matches and no default is present.