Can we solve this with switch statement?

Tell us what’s happening:
This is a long if else chain for golf problem. But it is eventually only evaluating the strokes. So can’t we solve it with switch statement like below? the console is throwing an error.

SyntaxError: unknown: Unexpected token (8:7)

   6 |     return names[0];
   7 |     break;
>  8 |   case <= par - 2:
     |        ^
   9 |     return names[1];
  10 |     break;
  11 | }

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 <= par - 2:
  return names[1];
  break;
}

return "Change Me";
// Only change code above this line
}

golfScore(5, 4);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36.

Challenge: Golf Code

Link to the challenge:

No this can not be solved with the switch statement, Because while declaring the case in switch statement the compiler will throw an error.
you can use a nested if-else statement for the above problem.

well, you can solve this with a switch statement, it’s not worth it

anyway, your syntax is not correct
you need to write
case (expression):
you can’t write case === 1 because === 1 is not a complete expression

there is only one way to make this work with a switch statement because you have two different cases for which there is a range of numbers, and that is:

   switch (true) {
      case par === strokes:
         return ...
      case par === strokes + 1:
         return ...
      ...
1 Like

Hi!

I have checked that as follows and it ALSO works!

switch(true) {
    case strokes === 1:
        return names[0];
        break;
    case strokes <= par - 2:
        return names[1];
        break;
     ............
     ............
 }
1 Like

Interesting. But i don’t understand why we are putting true as switch parameter? We are checking the value of strokes right?

Hi!

Check that link:

1 Like

yes, you want to check the value of strokes and par but you can’t translate strokes <= par - 2 in a case if you write switch (strokes) {...}
now, if it was only one case in which there was a range of numbers, you could use the default case, there are two - you can’t have two default cases. You could write additional logic inside the default case to distinguish between the two, if you really want to do it that way.

   switch (strokes) {
      ...
      default:
         return (strokes <= par - 2) ? names[1] : ...
   }
1 Like

I understand now. Thank you all for explaining and for your patience.