I tried changing numbers, plus i also tried removing and re-adding math floor but the outcome was still the same. It’s supposed to give different number every time but in my case it’s only giving one number as an output no matter how many times i write the code.
My code is
var thisIsNew = Math.floor(Math.random() * 6);
3
Answers
If you generate a single random number and store it in a variable, the contents of the variable won’t change across different outputs of the same unchanged variable.
Instead what you need to do is make a function that generates random numbers the way you like, and call that function multiple times:
will print 3 freshly generated random numbers.
thisIsNew
is a variable which is defined and initialized via this line:At this point you compute a randomized number between 0 and 1, multiply it with 6, so it will be between 0 and 6 and floor it, so it will be 0, 1, 2, 3, 4, 5.
Once the computation is over, this value is assigned to your newly created variable of
thisIsNew
, which, from that point onwards will have this value until you change it. So, when you later on refer tothisIsNew
, without changing its value, it will be the same. You can compute it again when needed.A neat way to do so is to have a randomization function, like
Usually a variable with a primitive value does not change the value. To get a different value, you need a function (callable value) and this returns the result of a function. Another solution could be an object with a property getter.
You could use an object, here
window
and create a property with a getter.