6/11 Having trouble with my code


#1

Hi,

I can't seem to get my code running. Here's what I'm using:

var myCondition = true;

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

soloLoop();

Everytime I try to run it, I'm getting the "Oops, try again. Did you log 'Looped once!' to the console?" error. Hope you can help me out!

Thanks!
Simon


#2

This is what I did:

var loop = true

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

soloLoop();

Comparing mine with yours, I don't think you're supposed to put your variable in your function.

Hope it helped!:smiley:


#3

Thanks for that @ragezapper! Worked like a charm. Would you know why it worked when the variable wasn't included in the function?


#4

Unfortunately, no. I should ask. @haxor789
Need some help here.


#6

Note the output of the console.log() statements just inside the function...

var myCondition = true;

var soloLoop = function (myCondition) {
    console.log(myCondition); // undefined
    while(myCondition) {
        myCondition = false;
        console.log("Looped once!");
    }
    console.log(myCondition); // undefined
};

soloLoop();
console.log(myCondition); // true

What does this show? Answer: That it is not only the one variable, but two. There is no argument in the function call, soloLoop() so the formal parameter of the function, which is locally declared implicitly, is undefined. That's why it logs that way at the start of the function.

Because the value is undefined the loop never executes. Consequently, the variable is not set to false. This explains the log out following the loop. Also, because the variable has the same name as the global variable, the global cannot be seen. It is said to be in the shadow of the local variable, and invisible from local scope.

Consider nothing changes except the argument in the function call,

soloLoop(myCondition);

This time the first log out will be true, so the loop will run and set the variable to false, which will log out after the loop. The final log out after returning from the function will still be true since this variable is unaffected by the function.

Is this starting to fall into place?


#8

Hi @mtf,

Thanks for the input! I have to admit that it's not all clear to me yet, but your input has helped me understand it to some degree.

Thanks!