1.2 - How does this loop?


#1

var understand = true;

while(understand){
understand=false;
console.log("I'm learning while loops!");
}

I don't understand how this while loop loops... What is it looping through - just the condition of true? This can't be a loop unless it also takes into the possibility of generating a "false" condition.

Could it be that this example is just a very ineffective use of demonstrating a while loop?

if I wanted to print "I'm learning while loops!", i could i have just typed, "console.log("I'm learning while loops!");


#2

A while loop runs until it encounters a false statement, like any other loop. In the example here it runs once, because, as it goes through the loop, understand becomes equal to false, but it still completes the loop before checking understand again. Here's another example,

var keepRunning = 10;
while (keepRunning >= 0) {
    keepRunning--;
    console.log(keepRunning);
}

And here's another,

var keepRunning = 10;
while (keepRunning == 0) {
    keepRunning--;
    console.log(keepRunning);
}

In the first example, it prints the numbers 10 through 0; but in the second it doesn't do anything, because keepRunning didn't equal 0.