Home > Back-end >  JavaScript - Prompt inside function doesn't appear on screen, but does outside the function
JavaScript - Prompt inside function doesn't appear on screen, but does outside the function

Time:05-31

I am building a rock, paper, scissors project which is supposed to take 5 rounds. The user will get a prompt and input either "rock", "paper", or "scissors". When I write the code like this:

let playerSelection = prompt("Rock, paper ou scissors?").toLowerCase();


let game = function() {
  for (let i = 0; i < 5; i  ) {

    compare(playerSelection, computerPlay);
      if (compare === "You win!") {
       playerScore  ;
      }
      else if (compare === "You lose!") {
        computerScore  ;
      }
      else if (compare === "It's a tie!") {
  
      }

 }
}

The prompt is prompted and I get to input something, however it only happens once and the loop doesn't work. When I put the prompt inside the loop, like this:

let game = function() {
  for (let i = 0; i < 5; i  ) {
    
    let playerSelection = prompt("Rock, paper ou scissors?").toLowerCase();

    compare(playerSelection, computerPlay);
      if (compare === "You win!") {
       playerScore  ;
      }
      else if (compare === "You lose!") {
        computerScore  ;
      }
      else if (compare === "It's a tie!") {
  
      }

 }
}

The prompt never shows up! How can I solve this and make it prompt 5 times?

CodePudding user response:

Well you are not calling the function. use

game();

after function definition

CodePudding user response:

I think there is some error in your compare function. checkout the snippet below its working fine.

const compare = function(playerSelection, computerPlay) {

  // write your logic here
  return "You win!";
}
let game = function() {
  for (let i = 0; i < 5; i  ) {
    
    let playerSelection = prompt("Rock, paper ou scissors?").toLowerCase();
    const outputs = ["rock", "paper", "scissor"];
    compare(playerSelection, Math.floor(Math.random()*3));
      if (compare === "You win!") {
       playerScore  ;
      }
      else if (compare === "You lose!") {
        computerScore  ;
      }
      else if (compare === "It's a tie!") {
  
      }

 }
}

game();

  • Related