-2

so this code does of course work:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var day;
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case  6:
        day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

</body>
</html>

but without the break; statement it doesnt:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var day;
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
    case 1:
        day = "Monday";
    case 2:
        day = "Tuesday";
    case 3:
        day = "Wednesday";
    case 4:
        day = "Thursday";
    case 5:
        day = "Friday";
    case  6:
        day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

</body>
</html>

I wonder why it will display "saturday" if i omit the break statement even saturday isnt ever the case since today is tuesday. Do you know why it will go in case 6 and output saturday instead of nothing when the break statement is omitted? thanks for you help.

Herrsocke
  • 272
  • 4
  • 13

2 Answers2

2

The reason you need break statement is because switch works differently. When you have multiple conditions like this, it will start from the match and then continue until the end or until it's interrupted with break. Thus, for Tuesday, the actual code flow is like this:

case 2:
    day = "Tuesday";
    day = "Wednesday";
    day = "Thursday";
    day = "Friday";
    day = "Saturday";

And you end up with Saturday. You can easily see this if you step through the code in a debugger (use Chrome dev tools, for example).

If you put break at the end of each case, then the flow will be like this:

case 2:
    day = "Tuesday";
    break;

And you end up with Tuesday.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
0

break is to end the execution of statements which should run only for that case. if you dont have break, the execution of statements will continue until it reaches the last case or default case.

Nik
  • 11
  • 1