Search code examples
javascripthtmldomdom-manipulation

Replace string value with emoji javascript


I'm learning to code in javascript, the below code is a rock paper scissor game. i want the output to display the respective emojis instead of text-Rock,Paper,Scissor.

how can i replace ["rock", "paper", "scissors"] with ["✊", "🤚", "✌"]

script.js


function getComputerChoice() {
  //const options = ["✊", "🤚", "✌"];
  const options = ["rock", "paper", "scissors"];
  const random = Math.floor(Math.random() * options.length);
  return options[random];
}

function getResult(playerChoice, computerChoice) {
  let score;
  if (playerChoice === computerChoice) {
    score = 0;
  } else if (
    (playerChoice == "rock" && computerChoice == "paper") ||
    (playerChoice == "paper" && computerChoice == "scissors") ||
    (playerChoice == "scissors" && computerChoice == "rock")
  ) {
    score = -1;
  } else {
    score = 1;
  }
  return score;
}

// ** showResult updates the DOM to `You Win!` or `You Lose!` or `It's a Draw!` based on the score. Also shows Player Choice vs. Computer Choice**


  rpsBtns.forEach(
    (btn) =>
      (btn.onclick = () => {
        const res = getComputerChoice();
        computerChoiceDiv.innerText = res;
        onClickRPS(btn.value);

        showResult(getResult(btn.value, res), btn.value, res);
      })
  );
}



playGame();

Solution

  • You can choose between either of those methods, and it's completely up to you. I find one advantage in following this method: Keep the options just like const options = ["rock", "paper", "scissors"] And you can have an object to map between the options string and their respective emojis like this:

    const emojis = {rock: "✊", paper: "🤚", scissors: "✌"};
    

    And just at the time of rendering the emojis on the screen you can take the emoji from emojis object like emojis["rock"]. So that in future if you want to replace the emoji with images or svg icon names, it'll be much easier.

    Just to your notice, like @scott-marcus said, opinion based questions aren't the kind of ones to be posted here. Soon someone may close this question for good. I hope this answer will help you