Search code examples
javascriptconditional-statementsternary

Ternary Condition for if { } else if { if { } else { } }


I want to change all the if else statements to ternary operator. Whats the ternary operator for this if else statements ?

  const compareHands = (playerChoice, computerChoice) => {
        // Update Text
        const winner = document.querySelector('.winner');
        const winnerIs = (who, isPlayerWin) => {

            winner.textContent = `${who} Wins!`;

            isPlayerWin ? pScore++ : cScore++;

            updateScore();
        };



        // Check for tie
        if (playerChoice === computerChoice) {
            winner.textContent = 'It Is A Tie!';
            // Check For Winner
        } else if (playerChoice === 'rock') {
            if (computerChoice === 'scissors') {
                winnerIs('Player', true);
            } else {
                winnerIs('Computer', false);
            }
        } else if (playerChoice === 'paper') {
            if (computerChoice === 'scissors') {
                winnerIs('Computer', false);
            } else {
                winnerIs('Player', true);
            }
        } else if (playerChoice === 'scissors') {
            if (computerChoice === 'rock') {
                winnerIs('Computer', false);
            } else {
                winnerIs('Player', true);
            }
        }
    }

Solution

  • Try like this. Though readability is a problem since there are too many nested if else which is replaced by ternary operator. true & false are replace with !0 & !1 respectively to shorten the statement

    playerChoice === computerChoice ?
      winner.textContent = "It Is A Tie!" :
      "rock" === playerChoice ?
      "scissors" === computerChoice ?
      winnerIs("Player", !0) :
      winnerIs("Computer", !1) :
      "paper" === playerChoice ?
      "scissors" === computerChoice ?
      winnerIs("Computer", !1) :
      winnerIs("Player", !0) :
      "scissors" === playerChoice && ("rock" === computerChoice ? winnerIs("Computer", !1) :
        winnerIs("Player", !0));