my conditional text is not reflecting on the page when the function is called

46 Views Asked by At

It seems the result variable is not defined, what did i do wrong?

In html I called the function using the the onclick attribute, giving both my buttons parameters.

In pickCompterMove() I used math.random to specify heads or tails.

My console does not detect any errors.

const text = document.getElementById('text');


function playGame(playerMove) {

  computerMove = pickComputerMove();
  let result = '';

  if (playerMove === 'heads') {
    if (computerMove === 'heads') {
      result = 'You win';
    } else if (computerMove === 'tails') {
      result = 'You lose';
    }
  } else if (playerMove === 'tails') {
    if (computerMove === 'heads') {
      result = 'You lose';
    } else if (computerMove === 'tails') {
      result = 'You win';
    }
  }
  text.innerText = result;

}

1

There are 1 best solutions below

1
beth On

It would be nice if you included HTML in the code. Your code may not have worked because the function pickComputerMove() wasn't stated, but called in the code.

function pickComputerMove() {
        // This function randomly picks either 'heads' or 'tails' for the computer's move
        return Math.random() < 0.5 ? 'heads' : 'tails';
    }

    function playGame(playerMove) {
        const text = document.getElementById('text');
        const computerMove = pickComputerMove();
        let result = '';

        if (playerMove === 'heads') {
            if (computerMove === 'heads') {
                result = 'You win';
            } else if (computerMove === 'tails') {
                result = 'You lose';
            }
        } else if (playerMove === 'tails') {
            if (computerMove === 'heads') {
                result = 'You lose';
            } else if (computerMove === 'tails') {
                result = 'You win';
            }
        }
        text.innerText = result;
    }
  <div id="text"></div>
    <button onclick="playGame('heads')">Play Heads</button>
    <button onclick="playGame('tails')">Play Tails</button>

In case you want to move out of what you already have and want a shorter line of code, you have the option below, works the same just shorter than the initial code:

function pickComputerMove() {
    // This function randomly picks either 'heads' or 'tails' for the computer's move
    return Math.random() < 0.5 ? 'heads' : 'tails';
}

 playGame = playerMove => document.getElementById('text').textContent = pickComputerMove () == playerMove ? 'You win':'You lose';