I don't understand why it's not correct: Selecting from Many Options with Switch Statements

Tell us what’s happening:
Is there something I’m missing?
Your code so far


function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch (val) {
case 1:
answer = "alpha";
case 2:
answer = "beta";
break;
case 3:
answer = "gamma";
break;
case 4:
answer = "delta";
break;
}



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

caseInSwitch(1);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Selecting from Many Options with Switch Statements

Link to the challenge:

Hello!

The break is missing.

If you omit it, the switch assigns the next value, and the next, and so on… until a break is found or the switch statement ends.

Try it on JavaScript Tutor - Visualize JavaScript code execution to learn JavaScript online to see the code live :slight_smile:.

Thanks didn’t see the missing break after case 1 :woman_facepalming:

1 Like

Hi there,

For case 1: you need to add a ‘break’; otherwise, you’re instructing js to move immediately to case 2. What happens here is tantamount to having created an OR case statement ; hence, case 1 answer (“alpha”) is negated==>>

case 1:
case2:
answer = “beta”;
break;

return answer;

Another suggestion would be to (make it a habit to) use a ‘default’ statement as a default return value; the reason behind is that, ‘what if ?’ the ‘end-user’ would input a ‘val’ value that is far-fetched from what you anticipate, that would leave a ‘blank’ return, which would not be a cool idea. ==>>

suggested example:

default:
return Value entered : ${val} is not valid! Enter a value within the range: 1 - 4 only;

Hope this helps.

Quote: “javaScript is sweeter the second time around!”

joMari

1 Like