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



var moonPhase = 'full';

switch (moonPhase) {
  case 'full':
    	console.log ('Howwwwlll!!');
  case 'mostly full':
  		console.log ('Arms and legs are getting hairier');
  case 'mostly new':
      console.log ('Back on two feet');
    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?


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


Thank you for the explanation!


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