storval
storval

Reputation: 21

Why does generating a random number outside of a loop, causes it to be always the same?

When I create a random number inside a while loop as a local variable everything works, but when I generate a random number as a global variable then I get stuck in an infinite loop.
I don't understand how and why this should make any difference. Goal is to output all the random numbers that are less than 0.7 with a While Loop.

Here is the code that creates an infinite loop:

let rnd = Math.random();
let continue = true;

while (continue) {
  console.log(rnd);
  if (rnd > 0.7) {
    continue = false;
    alert(rnd + ' is bigger than 0.7!');
  }
}

Here is the code that works (only thing that is changed is that the random number is generated within the while loop).

let continue = true;

while (continue) {
  let rnd = Math.random();
  console.log(rnd);
  if (rnd > 0.7) {
    continue = false;
    alert(rnd + ' is bigger than 0.7!');
  }
}

I'm not interested in creating this with another kind of loop, I'm just trying to understand the While Loop better.

Upvotes: -1

Views: 953

Answers (2)

Valoruz
Valoruz

Reputation: 194

It is because when you declare Math.random() as a variable it creates a binding with a random value which doesn't change. Example: 0.8.

And if it is less than or equal to 0.7 then it would result in an infinite loop because the value doesn't change with each iteration.

In the second example it works fine because it is declared locally and it's value changes with each iteration.

Hope you understood.

Upvotes: 1

AlexSp3
AlexSp3

Reputation: 2293

let rnd = Math.random(); 
let continue = true;


while (continue) {
console.log(rnd);
    if (rnd > 0.7) {
        continue = false;
        alert(rnd + ' is bigger than 0.7!');
    }
} 
  • Here, the random number generator will only execute one time, before the while loop. If th random number isn´t > 0.7, continue would be always true and it will be an infinite loop.

  • However, if the random number is generated locally in the while loop, in each loop a new number will be generated so you only need to wait for a rnd number > 0.7.

Upvotes: 1

Related Questions