While loop doesn't work?


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-ASGIv/2/4?curriculum_id=506324b3a7dffd00020bf661


So I'm trying to make a code that puts some numbers in an array and continues to pick one of these numbers until it has chosen number 4. However, it is looping infinitely and I don't understand why.

The code within the while-loop works when taken separately, and currentNumber is able to become 4. But as soon as I put the condition in there it won't stop looping.
Could someone please explain to me what I'm doing wrong?


var numbers = [];

console.log("Just some numbers:");
for (var i = 4; i <= 40; i += 9){
    console.log(i);
    numbers.push(i);
};

var currentNumber = numbers[4];

do {
    console.log("I want to draw number 4.");
}
while (currentNumber !== 4) {
    console.log("Nope, that's number " + currentNumber);
    var newPosition = Math.floor(Math.random() * 5);
    
    currentNumber = numbers[newPosition];
};

console.log("Got it!");


#2

while (condition) {
    // loop body
}

do {
    // loop body
} while (condition);

#3

Thank you! Guess I just didn't understand the whole do/while thing. :sweat_smile:
Now it makes a whole lot more sense why you would even want to do that.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.