Switch Statement Exercise - Confused

Hello,

I understand the concept of switch statements, but this question still confuses me slightly. I read both solutions and the second makes sense to me (in that solution, we set

case 4:
answer = ‘delta’,
break;

for example, making a direct connection with the blank string variable defined in the function). However, this code below confuses me because I do not see how the returned string values for each case would “connect” to substitute for the “answer” variable. Basically, how do the cases with returned values serve/substitute as the blank-stringed “answer” variable? Thanks.


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


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

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

Challenge: Selecting from Many Options with Switch Statements

Link to the challenge:

They don’t in this case because you are returning directly out of the case statements so it will never get to the last line of the function. This is a very common way handle something like this, although it would be simplified to:

function caseInSwitch(val) {
  switch(val) {
    case 1:
      return 'alpha';
    case 2:
      return 'beta';
    case 3: 
      return 'gamma';  
    case 4:
      return 'delta';
    default:
      return '';
  }
}

because there is no need for a break if you are returning - after the return the function ends.

So, to put it simply, in the first example (as is wanted in the challenge) you are using the switch to store the value in a variable and then returning it at the end. In this other way of doing it, we are just returning from each case statement. I actually prefer the second and it would probably be more common to see that. But I understand that FCC wants to keep it simple and easy to follow so they are starting off with the “longer” way of doing it.

Does that make sense?

1 Like

This cleared it up perfectly. I didn’t remember that return statements negate the need for a “break” statement, since it ends the function anyway. Thanks again.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.