Intro to While Loops Part 6


#1

var condition = true;
var soloLoop = function() {
while(condition) {
console.log("Looped once!");
var condition = false;
}
};

soloLoop();

I'm not entirely sure why it's not working. Could someone point out what I'm doing wrong because I can't seem to find the error.


6/11 Did you log ‘Looped once!’ to the console? for no obvious reason
#2

You're setting a global variable and then a different local variable in the while loop. This is causing an infinite loop as condition is never set to false globally. Make sure to remove the var from the while loop.


#3

You’re on a good track but it doesn’t create an infinite loop it doesn’t loop at all. By using var @arcsharp created a new variable and whenever this is done it is treated as if this declaration would be the first statement in the function (called hoisting if you want to google it). So the value is undefined not true and therefore for the loop is not run:

Code
var condition = true;
var soloLoop = function() {
console.log(condition); // see it is undefined not true or false
while(condition) {
console.log("Looped once!");
var condition = false;
}
};

soloLoop();

#4

Thank you for the explanation @haxor789 .

I did look up hoisting and now I understand. I was a little confused as to why it's undefined and not false. Then I read that hoisting only moves up declarations and not initialization. So I'm taking it as the variable "condition" got declared but it didn't get initialized to "false" thus it is undeclared.

I appreciate the explanation!