Switch directive

I’m wondering why the case statements aren’t deflecting code execution when false:

switch (prompt("What is the weather like?")) { 
case "rainy":
console.log("Remember to bring an umbrella.");
case "sunny":
console.log("Dress lightly."); 
case "cloudy":
console.log("Go outside.");
console.log("Unknown weather type!");
break; }

When typing in “sunny” into the console, it outputs both “dress lightly” and “go outside”. No break of course means that it continues on to evaluate “cloudy”, but why would that case execute if that wasn’t the string?

I guess you would have to ask the creator why he chose to implement switches that way. Some programming languages only execute the appropriate case, JS chooses to enter the switch at the relevant case and then execute all subsequent code until it encounters a break. While this might lead to bugs, it also allows for constructions like

  switch(prompt('what\'s the day?')) {
    case 'monday':
    case 'tuesday':
    case 'wednesday':
    case 'thursday':
    case 'friday':
      console.log('that\'s a weekday');
    case 'saturday':
    case 'sunday':
      console.log('it\'s weekend');

Because there’s no breaks, any weekday would end up in the friday-case (friday has a break), which would then inform you that it is in fact a weekday. This avoids code repetition since “console.log(‘that’s a weekday’)” applies to all weekdays, but is only entered once.

1 Like

Well, the Javascript switch case works in that manner. It is how it was created. As @Wayan said, it enables you to do cases otherwise not possible with this feature.

You can look up Javascript Switch Case . The documentation is detailed.

Hope this helps.

Happy Learning :slight_smile: