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.
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.
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 ...
...
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.