0

Working on a JavaScript Rock/Paper/Scissors game for a foundations Odin Project assignment that runs in the console. I made a function to compare playerSelection and computerSelection and determine win, lose, draw, or the playerSelection was not valid. The problem is, if for the playerSelection I input nonsense (i.e. asdf) It will correctly identify the input as invalid about 80% of the time, but will (seemingly) randomly return the result as a draw.

const playRound = (playerSelection, computerSelection) => {
// if and else if for win/lose are here.
else if 
        ((playerSelection.toLowerCase() && computerSelection) === ('rock' || 'paper' || 'scissors')) {
            return `It's a draw\nYou chose ${playerSelection}\nComputer chose ${computerSelection}`;
    } else return `Looks like your input was invalid\n${playerSelection}`
};

Why the inconsistent return?

Full code: https://github.com/justbkoz/rockPaperScissors/blob/main/rockPaperScissors.js

  • 4
    `=== ('rock' || 'paper' || 'scissors')` doesn't do what you think it does. – Barmar Apr 03 '21 at 22:44
  • 1
    Neither does `(playerSelection.toLowerCase() && computerSelection)` – Barmar Apr 03 '21 at 22:45
  • Unless the player selection is an empty string, that is equivalent to `if (computerSelection == 'rock')` – Barmar Apr 03 '21 at 22:46
  • 1
    Why not just `if (playerSelection.toLowerCase() === computerSelection)`? – Barmar Apr 03 '21 at 22:51
  • 1
    Also, why don't you convert the player's selection to lower case immediately after the prompt, so you don't have to write `toLowerCase()` 7 times? – Barmar Apr 03 '21 at 22:52
  • Appreciate the help! seems obvious once you point it out. I had been testing it by inputting "rock" as that was the shortest valid answer to type over and over... – justbkoz Apr 03 '21 at 23:00
  • What you input is irrelevant to that statement, unless it's empty. – Barmar Apr 03 '21 at 23:01
  • if I input paper or scissors I trigger a win or loss, unless the computerSelection is paper. Which like you pointed out, is not true when it gets to what is effectively if (computerSelection == 'rock') – justbkoz Apr 03 '21 at 23:09

0 Answers0