Sunday, 9 December 2018

JavaScript: Do I require break statement in default case of switch statement

If you added default case at the end of all the switch cases, then you do not require a break statement.

HelloWorld.js
function print_day_of_week(day){
  switch(day){
    case 1:
      console.log("Sunday");
      break;
    case 2:
      console.log("Monday");
      break;
    case 3:
      console.log("Tuesday");
      break;
    case 4:
      console.log("Wednesday");
      break;
    case 5:
      console.log("Thursday");
      break;
    case 6:
      console.log("Friday");
      break;
    case 7:
      console.log("Saturday");
      break;
    default:
      console.log("Not a valid day");
  }
}

print_day_of_week(10);

Output
Not a valid day

But if you add default case anywhere not at the end, then you should add break statement.

HelloWorld.js
function print_day_of_week(day){
  switch(day){
    case 1:
      console.log("Sunday");
      break;
    case 2:
      console.log("Monday");
      break;
    default:
      console.log("Not a valid day");
    case 3:
      console.log("Tuesday");
      break;
    case 4:
      console.log("Wednesday");
      break;
    case 5:
      console.log("Thursday");
      break;
    case 6:
      console.log("Friday");
      break;
    case 7:
      console.log("Saturday");
      break;
  }
}

print_day_of_week(10);

As you see above snippet, I added default case after case 2 and do not provided break statement inside default case.

When I ran above application, I seen below two messages.

Not a valid day
Tuesday

It is because, break is omitted, the program continues execution at the next statement in the switch statement.


Previous                                                 Next                                                 Home

No comments:

Post a Comment