6.solo flight


6.solo flight

my code is crashing the page

var hey=true;
var soloLoop = function(){while(hey){console.log("looped once");
  var hey=false;}



Ok well it shouldn't. It is not correct but it should not crash the page and I cannot reproduce this behavior.

The problem that I see is the following: You're experiencing the effects of shadowing and hoisting:

Shadowing: As you've learned in the exercise about functions, functions have their own scope. Meaning that when you declare a variable inside a function it is only accessible inside the function and doesn't exist for the outside world. Well shadowing occurs when there already is a variable outside of the function with the same name that you want to use inside of the function. To avoid ambiguity, inside the function only internal variable can be used (and global variables that have a unique name) therefore the global variable somehow lies in the shadow of the local one where it cannot be seen.

Long story short the variable hey that you declared inside your function is not the same variable hey that you declared outside of your function.

Now hoisting:

Now one could assume that this isn't a big deal because when you enter the function hey is the global variable that has a value of true and therefore the while loop should work and only then the second variable gets introduced.

Unfortunately this is not the case. What happens is an effect called hoisting meaning that the interpreter moves any declarations to the top of the scope meaning although you wrote:

    var soloLoop = function(){
      while(hey){console.log("looped once");
         var hey=false;} //after entering the while loop

the interpreter will always read it like this:

    var soloLoop = function(){
      var hey;
      while(hey){console.log("looped once");
         hey=false;} //after entering the while loop

Meaning that the first thing you do is to declare the new variable and thereby make the global hey inaccessible from inside the function. Now as an undefined variable has a value of ... well you probably guessed it: undefined and as undefined is treated like false, the loop will not even be entered once.

So from what i can see your code should not work for the explained reasons but it shouldn't crash the site (run as infinite loop) either.

To fix this just get rid of the var inside of the function or and that is the better way get rid of the global variable and declare var hey = true; as the first statement inside of your function. That would make sense as that is the only place where you use it anyway, isn't it? And this will work as well if you call the function twice, try this with the global version :slight_smile:


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