I’m new to JS and I’m trying to do an assignment on codewars. It’s supposed to be a rock,paper, scissors game and to return which player won or if there was a draw. I tried using switch case for this solution, however in some cases it returns the wrong answer. I know it can be solved using the if statement, however I am curious why my solution does not work. Could someone explain? Thank You in advance 🙂
Here is what I tried:
let rps = (p1, p2) => {
switch (p1,p2){
case "scissors" && "paper":
return "Player 1 won!";
break;
case "scissors"&& "rock":
return "Player 2 won!";
break;
case "scissors"&& "scissors":
return "Draw!";
break;
case "paper"&& "paper":
return "Draw!";
break;
case "paper"&& "scissors":
return "Player 2 won!";
break;
case "paper"&& "rock":
return "Player 1 won!";
break;
case "rock"&& "rock":
return "Draw";
break;
case "rock"&& "paper":
return "Player 2 won!";
break;
case "rock" && "scissors":
return "Player 1 won!";
break;
}
};
4
Answers
switch only supports one value. To use it as a switch you would need to concatenate the strings.
other option is a nested switch
That is not how switch works. Switch looks for exact value match to the given statement.
You want to use either if like so:
Or, if you insist of using switch, compare for example
string
value of the combination, like so:Also, note that you don’t need to break after return. Return statements exits your function immediately.
A
switch
statement only takes one expression. Note thatp1,p2
applies the comma operator, which will result in the value ofp2
. Yourcase
expressions only check one expression. Also here the&&
operator will evaluate to one of both operands.There are a few things you can do to reduce the code repetition here:
So, you can do this:
Using the same logic, but putting it in one expression:
A switch checks a single condition. You can swap the check, however, and test for true given a check of the two arguments in each case.
Note, you should also use a plain function or
const
instead oflet
, unless you want to reassignrps
later in the same scope. Also, thereturn
means you don’t need abreak
after eachreturn
. And you don’t have a default return (doh!). You can also group the outcomes, since the fall through outcomes all return and stop the case matching.