The position of default case in switch statement

***actually according to Mozilla it doesn’t matter where you place default case as long you type break statement after it ****
function switchOfStuff(val) {
var answer = “”;
// Only change code below this line
switch(val){
default:
answer = “stuff”;
break;
case ‘a’:
answer= “apple”;
break;
case ‘b’:
answer = “bird”;
break;
case ‘c’:
answer = “cat”;
break;

}

// Only change code above this line
return answer;
}

// Change this value to test
switchOfStuff(1);

Do you have a question or are you just looking for feedback?

It’s correct that the default case will be triggered if none of the other cases match. In general flow will continue after a match unless there is a break, so this can actually be abused by doing something like:

default:
foo()
case 'something':
bar()
break;

Which means bar alone gets executed if ‘something’ matches, but if not, foo and then bar get executed. I wouldn’t generally want to see this style of code since it’s “clever”, but it’s worth being aware how it works so you don’t accidentally write code in this fashion.

1 Like