Understanding more about the while loop

I’m randomly generating numbers inside of an array.

Here’s my code:


var max = 10,
    lowest = 1,
    store = [];

while(store.length < max) {
    var values = Math.floor(Math.random() * max) + 1;
    if(store.indexOf(values) === -1) {
        store.push(values);
    }
}

store;

The code works perfectly fine, but when I move the values variable outside of the while-loop and declare it above the while loop scope, it causes an infinite loop. Is this because the while-loop needs the values variable to keep repeating itself in it’s scope?

Runs normally for me when I tested the above code.

Yes it works perfectly fine, but I’m trying to figure out why is it that if I declare the values variable outside the while-loop and declare it above the while loop scope, why it causes an infinite loop?

I’m wondering is this because the while-loop depends on the values variable to be repeated multiple times?

The Jsfiddle example you were given has values declared before the while loop, which does not have a different variable scope.

Can you post a full code example that demonstrates the problem?

Sure…


var max = 10,
    lowest = 1,
    store = [];
    
var values = Math.floor(Math.random() * max) + 1;

while(store.length < max) {
    if(store.indexOf(values) === -1) {
        store.push(values);
    }
}
 
store;

The code example above causes an infinite loop, because the values var declaration (with the value assigned) is outside of the while loop. I’m just trying to figure out why does it causes an infinite loop when the values variable (value assigned to it) is outside of the while loop’s block?

But when the values is inside the while-loop, it doesn’t cause an infinite loop…

For example…


var max = 10,
    lowest = 1,
    store = [];
 
while(store.length < max) {
    var values = Math.floor(Math.random() * max) + 1;
    if(store.indexOf(values) === -1) {
        store.push(values);
    }
}
 
store;

Sorry about the confusion…

You’re setting “values” to a random number. When you set it inside the while loop, then you’re getting a new number for every iteration of the loop. But when you set it outside the loop, then the value of “values” never changes after that. Your “if” statement prevents the same number from being pushed more than once, so if “values” never changes, then you’ll never push more than one number.

So the while loop does depends values variable, otherwise it will cause an infinite loop.

Thanks.

I don’t understand your understanding.

The values gets declared to have a different value on each iteration of the loop inside it’s block, since it depends on the values on each iteration.

Does that make since?

I understand what Jeff Mott is talking about.