0

Some extra info: This is connected to an html file of code, but the html code doesn't show because it's in a different file, and I can't be bothered to fetch it. When I run this, the console shows a random number from 1-10, but the textContent ALWAYS shows "you rolled a 1". Does anyone know why this happens?

//Random Number 
function randomRange() {
  return Math.floor(Math.random() * 10);
}
var randomNumber = randomRange()
console.log(randomNumber);

//button changing onClick
const button = document.querySelector("#button");

function test() {
  button.style.color = "red";
  button.style.background = "black";
  if (randomNumber = 0) {
    button.textContent = "You Rolled a 0"
  } else if (randomNumber = 1) {
    button.textContent = "You Rolled a 1"
  } else if (randomNumber = 2) {
    button.textContent = "You Rolled a 2"
  } else if (randomNumber = 3) {
    button.textContent = "You Rolled a 3"
  } else if (randomNumber = 4) {
    button.textContent = "You Rolled a 4"
  } else if (randomNumber = 5) {
    button.textContent = "You Rolled a 5"
  } else if (randomNumber = 6) {
    button.textContent = "You Rolled a 6"
  } else if (randomNumber = 7) {
    button.textContent = "You Rolled a 7"
  } else if (randomNumber = 8) {
    button.textContent = "You Rolled a 8"
  } else if (randomNumber = 9) {
    button.textContent = "You Rolled a 9"
  } else if (randomNumber = 10) {
    button.textContent = "You Rolled a 10"
  }
};
Barmar
  • 741,623
  • 53
  • 500
  • 612
CGCG
  • 9
  • 2
  • 2
    `if (randomNumber = 1)` - that's assignment, not comparison. Did you maybe mean `==` – Tim Lewis Oct 12 '22 at 19:32
  • 1
    Also, `button.textConent = \`You rolled a ${randomNumber}\``; Don't need those `if` statements at all. – Tim Lewis Oct 12 '22 at 19:33
  • For more clarity, `if (randomNumber = 0)` is basically the same as `if (false)`, while `else if (randomNumber = 1)` is basically `else if (true)`, so your code stops on that 2nd condition _every time_. Hence why you always got `You Rolled a 1` every time instead of `You Rolled a 0`. This is a common mistake many programmers make, and there are cases for assignment in an `if()` statement, but in your case, this was a simple typo/case of using the wrong operator. – Tim Lewis Oct 12 '22 at 19:42
  • I don't know if you will see this Tim Lewis, but thank you for the help! – CGCG Oct 13 '22 at 00:35
  • I did, and you're quite welcome Happy coding! – Tim Lewis Oct 13 '22 at 00:58

0 Answers0