Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The break Keyword

When JavaScript encounters a break keyword, it exits the switch block.

This stops further execution within the switch block.

It is not required to include a break statement for the last case in a switch block, as the block will end there regardless.

Note: If you omit the break statement, the next case will execute even if the evaluation does not match that case.

The default Keyword

The default keyword designates the code to execute if none of the cases match.

Example

The getDay() method returns the day of the week as a number from 0 to 6.

If today is neither Saturday (6) nor Sunday (0), display a default message:

switch (new Date().getDay()) {
  case 6:
    text = “Today is Saturday”;
    break;
  case 0:
    text = “Today is Sunday”;
    break;
  default:
    text = “Looking forward to the Weekend”;
}

The resulting text will be:

Eagerly anticipating the weekend!

The default case does not need to be positioned as the last case in a switch block.

Example

switch (new Date().getDay()) {
  default:
    text = “Looking forward to the Weekend”;
    break;
  case 6:
    text = “Today is Saturday”;
    break;
  case 0:
    text = “Today is Sunday”;
}
If the default case is not the last one in the switch block, be sure to end it with a break statement.

Common Code Blocks

Sometimes you may want multiple switch cases to execute the same code.

In this example, cases 4 and 5 share one code block, while cases 0 and 6 share another.

Example

switch (new Date().getDay()) {
  case 4:
  case 5:
    text = “Soon it is Weekend”;
    break;
  case 0:
  case 6:
    text = “It is Weekend”;
    break;
  default:
    text = “Looking forward to the Weekend”;
}