# Golf Code Challenge switch statement

Golf Code Challenge switch statement
0

#1

Hi, I am trying to do the golf code challenge. When I do it with the if/else statements the code is working properly. But when I try to do it with the switch statement it is not working. I would like some help to know what is wrong with my switch statement.

Here is my if/else statement which is working perfectly

``````function golfScore(par, strokes) {
// Only change code below this line

if (strokes==1) {
return "Hole-in-one!";
} else if (strokes<=par-2) {
return "Eagle";
} else if (strokes==par-1) {
return "Birdie";
} else if (strokes==par) {
return "Par";
} else if (strokes==par+1) {
return "Bogey";
} else if (strokes==par+2) {
return "Double Bogey";
} else if (strokes>=par+3) {
return "Go Home!";
}
// Only change code above this line
}

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

Here is my Switch statement which ain’t working for some values while testing.

``````function golfScore(par, strokes) {
// Only change code below this line
var result=" ";
switch (strokes) {
case 1:
result="Hole-in-one!";
break;

case (strokes<=par-2):
result="Eagle";
break;

case par-1:
result="Birdie";
break;

case par:
result="Par";
break;

case par+1:
result="Bogey";
break;

case par+2:
result="Double Bogey";
break;

case (strokes>=par+3):
result="Go Home!";
break;
}

return result;

// Only change code above this line
}

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

#2

I’m not sure if this can be solved with a `switch` statement. `switch` statements are good if the variable you’re testing has a (reasonably) finite number of values it can hold. Of if you want to do something with specific values, and deal with the rest (by using `default`). However, `switch` is not very useful when dealing with ranges, especially when you have an indefinite range on both ends (like in this problem) because there’s only one `default` case you can use.

You can’t do `case (strokes <= par - 2)` because then you’ll be comparing the actual value of `strokes` (a number) with the value of evaluating `strokes <= par - 2` (a boolean).

#3

You can use an expression in each case and use switch(true) which will check which expression evaluates to true.

I will not give you the whole solution, but if you just wanted to check for Hole-in-one and Eagle, you could do:

``````function golfScore(par, strokes) {
// Only change code below this line
var result=" ";
switch (true) {
case strokes === 1:
result="Hole-in-one!";
break;

case (strokes<=par-2):
result="Eagle";
break;
}
return result;
// Only change code above this line
}
``````