While loop infinite after var = false?


#1


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


Okay so here's my problem. I can run this code below:


var goTime = false;
var number = 6;

for(i = 0; i < number; i++) {
do {
    console.log("Printed out" + " " + number + " " + "times.");
} while(goTime);
};

... and it works without a hitch. However where I am getting really confused
 is when I try to experiment with it and try it this way with the goTime var starting
 off equaling true and it throws me an infiniloop:

var goTime = true;
var number = 6;

for(i = 0; i < number; i++) {
do {
    console.log("Printed out" + " " + number + " " + "times.");
} while(goTime) {
goTime = false;
};
};

What am I doing wrong?


#2

I've moved your code around a bit, but without changing anything, so that you can (maybe) more easily see what the problem is.

var goTime = true;
var number = 6;

for(i = 0; i < number; i++) {

    do {
        console.log("Printed out" + " " + number + " " + "times.");
    } while(goTime) 

    { goTime = false; };
};

Your do loop is going to keep looping as long as goTime is true. You have nothing in the loop to make goTime false so it just keeps looping.

Sticking goTime = false in curly braces after your loop isn't doing anything to help here.

Do you see how that works now?


#3

Maybe... Is that problem that 'goTime = false' isn't connected to the 'while loop' so it never stops or because the 'while loop' is outside of the 'do' curly brackets?

My understanding at the moment is that the 'do' tells the 'while loop' to run once regardless of being true or false and then the 'while loop' checks for a reason to stop inside its own curly brackets. Or is it just a syntax error?

What would be the correct way of writing this to make it function?


#4

Yes, that's right. The do...while statement never ends because every time while(goTime) is checked, goTime is always true. As long as goTime is true the loop will run again, it will never go on to the next statement. It won't say "I see goTime is true so I'm going to loop again, but just for fun, let's just check the next line or two anyway."

We are talking about do...while statements here, maybe you are confusing that with a while statement? Don't try to mash these two things together:

do...while statement:

do {
   statement
} while (condition);

while statement:

while (condition) {
  statement
}

That will depend on what you are trying to accomplish, I'm not quite sure what your plan is there. A function looks like this:

var myFunction = function() {

   all your code goes in here

} // end of myfunction

#5

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