JavaScript Rock, Paper, Scissors game

Published on
7 mins read
––– views

Why Switch Statements?

If you write this game using if statements, this code gets way too complex to read and debug. We don't want that.

What is good code?

🤝 Easy to read

🤝 Easy to explain

🤝 Easy to write

🤝 Easy to understand

🤝 Commented or code is simple enough that comments aren't required

I'm sure by using some senior level magic, you can make this code even shorter, but short code doesn't mean better. In production or working with a team, your teem needs to be able to understand what you have written.

If you do some magic tricks, make everything so complex but short, that isn't useful. Writing code is easy, understanding what the heck you have written last year is hard. Never forget that.

I will explain the code step by step and write the whole code at the bottom.


First, we declare our function, and pass a parameter. scoreWin =2 parameter has a default value. If user enters no value to invoke the function, this function will and use the default value, 2

We also declare playerScore, computerScore and the final result

function playGame(scoreWin = 2) {
  let playerScore = 0;
  let computerScore = 0;
  let finalResult = "";
// more code below

scoreWin parameter determines how many rounds we win in order be the champion 🏆🥇. That's why we need a while loop. While Our or computer's score is less than scoreWin this code will run.


We need to get user input, well I wouldn't like to spell "rock" and "paper" every single time that I want to play, no need to mention "Scissors". You got the point. So, taking the input as a number, or would improve the user experience.


what if user enters something else? We need to check that too. if statement will make sure the input is between 1 and 3. If it isn't the user will face the prompt again.

while (playerScore < scoreWin && computerScore < scoreWin) {
    let playerChoice = prompt("Enter Number (1🪨 | 2📄 | 3✂️):");
    if (playerChoice < 1 || playerChoice > 3) {
      playerChoice = prompt("Enter Number (1🪨 | 2📄 | 3✂️):");
    }


Here, we will generate a random number for the computer, and assign that number to rock, paper or scissors. Also, we will need to convert the user input.

We can create two switch statements, one for player and one for computer, or use very long form of if statements. On this example, we will use objects and you will see why.

So, computerChoice is generated by a random number generator and it's 1, 2 or 3.

User inputs 1 2 or 3 as well, so, we could combine that logic inside an object. choices will have 3 properties, each is an option in the game.

After that, we will assign playerChoice to choices[THIS IS 1, 2 or 3] and it will be equal to rock, paper or... You know it. Same logic is applied for the computerChoice as well.

    let computerChoice = Math.floor(Math.random() * 3) + 1;

   const choices = {
  "1": "rock",
  "2": "paper",
  "3": "scissors"
};

playerChoice = choices[playerChoice];
computerChoice = choices[computerChoice];


This part defines the winner. first, we need to create a string with playerChoice and computerChoice and use that inside the switch statement. " " will work as an empty space, to make the code more readable. We will test each possible scenario for the player. All of these cases will make the player the winner. So, we can combine them all. No need to write case, then finalResult and ++ score and break the case. We can write cases on top of each other, and if either of them is true, rest of the code will run and break.


The logic is same for the computerChoice too, it's a list of scenarios that computer would win. When the one of the cases are true, we will console log the winner, and what they picked.


default case will be invoked if the round is tie.

 switch (playerChoice + " " + computerChoice) {

      case "rock scissors":
      case "rock scissors":
      case "paper rock":
      case "scissors paper":
        finalResult = `P 🏆 ➡️ ${playerChoice}
        beats ${computerChoice}`;
        playerScore++;
        break;
      case "rock paper":
      case "paper scissors":
      case "scissors rock":
        finalResult = `P 😭 ➡️ ${computerChoice}
        beats ${playerChoice}`;
        computerScore++;
        break;
      default:
        finalResult = "Tie!";
        break;
    }


Here is the whole while loop take a look and try to understand it. The last console.log prints the finalResult that is retuned by the switch statement.

while (playerScore < scoreWin && computerScore < scoreWin) {
    let playerChoice = prompt("Enter Number (1🪨 | 2📄 | 3✂️):");
    if (playerChoice < 1 || playerChoice > 3) {
      playerChoice = prompt("Enter Number (1🪨 | 2📄 | 3✂️):");
    }

    let computerChoice = Math.floor(Math.random() * 3) + 1;

   const choices = {
  "1": "rock",
  "2": "paper",
  "3": "scissors"
};

playerChoice = choices[playerChoice];
computerChoice = choices[computerChoice];

    switch (playerChoice + " " + computerChoice) {

      case "rock scissors":
      case "rock scissors":
      case "paper rock":
      case "scissors paper":
        finalResult = `P 🏆 ➡️ ${playerChoice} beats
         ${computerChoice}`;
        playerScore++;
        break;
      case "rock paper":
      case "paper scissors":
      case "scissors rock":
        finalResult = `P 😭 ➡️ ${computerChoice} beats
         ${playerChoice}`;
        computerScore++;
        break;
      default:
        finalResult = "Tie!";
        break;
    }
    console.log("Round result: " + finalResult);
  }

Let's move on. If you remember scoreWin parameter from the function. We will compare playerScore and computerScore to the scoreWin. If playerScore is equal to scoreWin it will print that Player has won, and it's score. Same logic applies if computer wins. This is called as ternary operator.

 finalResult = (playerScore === scoreWin) ?

    "🥇P: " + playerScore + "🥈C:" + computerScore :

    (computerScore === scoreWin) ?

    "🥇C: " + computerScore + "🥈P:" + playerScore :
    result;


  return finalResult;

and this is how we invoke the function, and print the final result.

const gamePlay = playGame();
console.log("Final: " + gamePlay);

Here is the whole code

function playGame(scoreWin = 2) {
  let playerScore = 0;
  let computerScore = 0;
  let finalResult = "";

  while (playerScore < scoreWin && computerScore < scoreWin) {
    let playerChoice = prompt("Enter Number (1🪨 | 2📄 | 3✂️):");
    if (playerChoice < 1 || playerChoice > 3) {
      playerChoice = prompt("Enter Number (1🪨 | 2📄 | 3✂️):");
    }

    let computerChoice = Math.floor(Math.random() * 3) + 1;

   const choices = {
  "1": "rock",
  "2": "paper",
  "3": "scissors"
};

playerChoice = choices[playerChoice];
computerChoice = choices[computerChoice];

    switch (playerChoice + " " + computerChoice) {

      case "rock scissors":
      case "rock scissors":
      case "paper rock":
      case "scissors paper":
        finalResult = `P 🏆 ➡️ ${playerChoice} beats
         ${computerChoice}`;
        playerScore++;
        break;
      case "rock paper":
      case "paper scissors":
      case "scissors rock":
        finalResult = `P 😭 ➡️ ${computerChoice} beats
         ${playerChoice}`;
        computerScore++;
        break;
      default:
        finalResult = "Tie!";
        break;
    }
    console.log("Round result: " + finalResult);
  }

  finalResult = (playerScore === scoreWin) ?
    "🥇P: " + playerScore + "🥈C:" + computerScore :
    (computerScore === scoreWin) ?
    "🥇C: " + computerScore + "🥈P:" + playerScore :
    result;


  return finalResult;
}

let gamePlay = playGame();
console.log("Final: " + gamePlay);

Closing Words

Is this the best way to write this? I do not know, but it uses many different methods with simple enough to understand practices. This simple code uses fallbacks, default parameters, switch statement, while loop, ternary operator, and objects. All in one.