Home > Back-end >  first JS random number to guess game
first JS random number to guess game

Time:02-24

I have slight problem with my first guessing game, it should draw random number between 1-10, but it return "1" every time. What's wrong in here? Thanks.

function guessGame() {
  let randomNr = Math.floor(Math.random() * 11);
  console.log(randomNr)
  let guess;
  do {
    guess = prompt("Guess number 1-10");
    console.log(guess, randomNr);
    if (randomNr > guess) {
      console.log("You guessed too low");
    } else if (randomNr < guess) {
      console.log("Guess was too high");
    }
  } while (guess !== randomNr);
  console.log("You Won");
}

guessGame();

CodePudding user response:

It appears your random number generator is working correctly. One thing to note though since you define randomNr outside of the do while loop it will only create a random number when guessGame() if first run, but it won't change the number on each guess. If you would like it to change number after each guess you could move let randomNr = Math.floor(Math.random() * 11); into the do while loop.

  • Related