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


#1

Hey! I do not understand why I keep getting the error msg "Did you log ‘Looped once!’ to the console?"...
Could anyone please explain why?....

var condition = true;

var soloLoop = function(){
//Your code goes here!
while(condition){
console.log("Looped once!");
var condition = false;
}
};

soloLoop();


#2

i added a console.log, check out this code:

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

soloLoop();

it will log condition, which will show you it is undefined, so i would define your variable inside your function


#3

Hey @ana_z! On your while loop you cant just say while(conditon), instead of that change it to while(conditon==true) Hope this helped!


#4

not true, you can just have a while loop with just a condition, this just means the condition is checked if it is true (but not compared to something)


#5

Thank you very much @stetim94!!

It was really all about declaring condition inside the function!

Great day to you!


#6

Actually the problem is that you use var condition in your function which leads to a feature called hoisting ending up at what @stetim94 described. Also this seems to be similar to this topic, maybe one could make a longer post somewhere.


#7

By pulling the variable condition into the function, I was successfully able to execute this function.

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

soloLoop(condition);

#8

Right, I guess because it's creating a local variable named "condition" and the while loop was referencing the global variable?


#9

The while loop uses condition as if it refers to the global variable, the problem is that it refers to the local one. The reason is a feature called hoisting meaning whenever you use var variableName inside of a function you create a new local variable inside of this function and even if this is the last statement in your function the declaration will be treated as if it was the first statement of this function. Meaning although var condition =false comes pretty late a new variable condition is created as the first thing in the function. Which leads to the problem that now condition is a new and therefore undefined variable instead of the expected global variable with the value of true.