Using switch() with Golf Code instead of if/else

Tell us what’s happening:
yes, i knew i could use chaining of if/else-if statements but this wouldn’t work when i tried using it with a switch() case. particularly the cases with a comparison operator. can anyone please explain why my code isn’t working?.. Thank you!

Your code so far


var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
  // Only change code below this line
  switch(strokes){
    case(1):
    return names[0];
    break;

    case (strokes) <= (par -2):
    return names[1];
    break;

    case(par -1):
    return names[2];
    break;

    case (par):
    return names[3];
    break;

    case (par +1):
    return names[4];
    break;

    case (par + 2):
    return names[5];
    break;

    case strokes >= (par +3):
    return names[6];
    break;
  
    default:
    return "Change Me";
  }
  // Only change code above this line
}

// Change these values to test
golfScore(4, 7);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/golf-code

The second and seventh cases in your switch are not numbers (they are logical checks, true or false) but you are checking to see if they match a number (the value of strokes).

Switch works by checking each case to see if it matches a value. This isn’t a good use case for switch because two of the things you need to check do not fit into that model. Switch works well when you have a set of known values of the same type that you want to switch between.

1 Like

thanks a lot for the information. now, i know better!