Switch statement - is the break statement required, or not, after the default scenario?


#1


https://www.codecademy.com/courses/learn-javascript/lessons/control-flow/exercises/switch?action=lesson_resume&link_content_target=interstitial_lesson


var moonPhase = 'full';
moonPhase='asd';

switch (moonPhase) {
  case 'full':
    	console.log ('Howwwwlll!!');
                 break;
  case 'mostly full':
  		console.log ('Arms and legs are getting hairier');
    						break;
  case 'mostly new':
      console.log ('Back on two feet');
    						break;
  default:
    console.log ('Invalid item');
//if I don't write the break; statement on this line, the code behaves the same; is this mandatory here? 
 // Or is it required with other functions and operations later on?
}


#2

Here are two important points. Break statements are optional and the default clause does not have to be the last statement.

In your example, since the default clause is last (and there is not other code afterwards in the the switch statement) the code will perform exactly the same with or without a break statement in the default clause.

Reference: Mozilla - switch statement, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling


#3

Thank you for the explanation!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.