Replacing If Else Chains with Switch drill

Not certain why this code is failing. Any constructive help would be very welcome as I’m tired of beating my head against the wall we call JavaScript.

Your code so far


function chainToSwitch(val) {
  var answer = "";
  // Only change code below this line
  switch(val){
    case 1:
    answer = "Marley";
    break;
    case 2:
    answer = "The Answer";
    break;
    case 3:
    answer = "There is no #1";
    break;
    case 4:
    answer = "Missed me by this much!";
    break;
    case 5:
    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 (Macintosh; Intel Mac OS X 10_14_2) 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

in this case val is 7 and you don’t have a case for that. You don’t have a case for any of the possible values that were in the if ... else chain

the value you put in front of case is the value that will make so that the code below that case is executed

2 Likes

got it-thank you! I think I’ve been at this for too many hours and I’m going blind. :smile:

Glad you solved your issue. I just wanted to add that it is considered best practice to include a default: case at the bottom of switch blocks to handle situations where the input doesn’t comply with any of the expected cases. For example:

switch(val){
    case 1:
    answer = "Marley";
    break;
    case 2:
    answer = "The Answer";
    break;
    case 3:
    answer = "There is no #1";
    break;
    case 4:
    answer = "Missed me by this much!";
    break;
    case 5:
    answer = "Ate Nine";
    break;
    default:
    answer = "Value not found!" // or simply an empty string: ""
    break;
  }
1 Like

Ah, thank you! I’m new to switch. The classes I’ve take didn’t mention it at all. Don’t know why as it seems like a nice way to do things.