Sunday 9 December 2018

JavaScript: Do I need to define default clause at last in the switch case

switch statement is used to match an expression against multiple expressions. Syntax of the switch case looks like below.

switch (expression) {
  case label_1:
    statements_1
    [break;]
  case label_2:
    statements_2
    [break;]
    ...
  default:
    statements_def
    [break;]
}

If the expression does not match to any label, then default case is executed.

One thing to remember is, you no need to define the default case at the end.

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;
    default:
      console.log("Not a valid day");
      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 example, I defined default case after case 3. When you ran above application, you can see below message in the console.


Not a valid day

Previous                                                 Next                                                 Home

No comments:

Post a Comment