user11379763
user11379763

Reputation:

Random Number Generator Inside a var element is giving the same output each time its called on

So I'm trying to make a JS project that involves RNG (random number generation).

I'm using a var object with the random number generator in it. Heres an example of what I'm talking about:

var RNG = Math.floor(Math.random() * (863 - 768 + 1)) + 768;
document.getElementById("output").innerHTML = RNG +"&nbsp"+ RNG +"&nbsp"+ RNG;

I'm expecting this to give 3 different random numbers in the element with the ID "output". I instead get 3 of the same random number. What can I do to get 3 different random numbers instead of 3 of the same random numbers?

Upvotes: 1

Views: 328

Answers (1)

Anis R.
Anis R.

Reputation: 6902

Try using a function instead of a variable. A variable's value gets computed only once (unless you re-assign it later on) and then the result is saved in it for future uses. So a function is more adequate to your problem.

Something like this:

function RNG() {
    return Math.floor(Math.random() * (863 - 768 + 1)) + 768;
}

document.getElementById("output").innerHTML = RNG() +"&nbsp"+ RNG() +"&nbsp"+ RNG();

Upvotes: 5

Related Questions