Replacing If Else Chains with Switch #can you please tell me where my fault is?

Tell us what’s happening:

Your code so far


function chainToSwitch(val) {
  var answer = "";
  // Only change code below this line
  
 switch(val){
   case 1:
    return answer = "Marley";
    break;
  case 2: 
   return  answer = "The Answer";
    break;
  case 3: 
   return answer = "There is no #1";
    break;
  case 4:
   return answer = "Missed me by this much!";
  break;
   case 5:
    return answer = "Ate Nine";
    break;
  }
  
  // Only change code above this line  
  return answer;  
}

// Change this value to test
chainToSwitch(7);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch/

There is a seven passed here, your code doesn’t do anything with a 7.

case 1: is the same as if (val === 1)

your code is not written to deal with he various values that the if statement was dealing with, examples are 7, and 42

Also, in each switch statement you do something like:

return answer = "Marley";

You don’t need a return in the switch statement. You can use return in a switch, but that will return out of the function. You will never reach that final return statements (assuming you add a default.) So, you don’t really need the variable answer - you can just return what you want. Or, you can just assign answer inside the switch and return answer at the end. Either works. Doing both is wrong. It may work, but it will raise eyebrows.

1 Like