-2

This is my general code (in JavaScript):

let x = Math.floor(Math.random()×6)+1);

if (x=1){
   do this
} else if (x=2){
   do that
} else if.... and so on. 

Whenever I test this code in a browser, only actions that could happen in the {do this} section happen. x is being locked as 1, even though it is meant to be a fair 6 sided die. Any ideas why this is happening, and how I can fix it?

Syed Mehtab Hassan
  • 1,297
  • 1
  • 9
  • 23
DylanK25 _
  • 15
  • 1

2 Answers2

2

The = operator in JavaScript is for assignment. x=1 will always return true because that is an assignment that will never fail. To test for equality use == (equality with conversion) or === (strict equality).

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You have your if (x=1) assigning the value of 1 to x, rather than checking if it's equal to it. This results in it always returning TRUE. Using a pair of == (or ===) will solve this.

Nathan
  • 31
  • 5