While loop not calling variable outside of the function: what's the logic?


#1

I understand that in "Solo Flight" section, the correct answer is:


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

soloLoop();

However, what if I want to refernce on a universal variable (var i = true being outside of the function)? When I tried it, it was blank - I assumed that it ran and automatically got var i = false so the console.log() never prompted.

What does the code need to be able to call on a universal variable?


#2

The code doesn't need anything extra to call on a global variable.

What is it that you mean by "it was blank"?


#3

This is what I typed, and what the console returned:


#4

This might be a problem with the CC parser itself.

Did the console, in fact, log "Looped once!"?


#5

No, it was blank, However I did later find out that if I modified the actual function into:
var soloLoop = function(i)

and invoked it via: soloLoop(i), then the console showed.


#6

This might simply be contained to Codecademy. AFAIK, this will work in the real world.

Humor me, though. Prefix i in the loop with this.

So while (this.i).

Also remove the redefinition of i in the loop. Change it to this.i = false.

Let me know if that works.


#7

It works!

also, I copied my own code to the actual browser console and it also returned blank

(The code modified as per your instruction on top, the original code I made on the bottom)


#8

Alright, cool. (btw the browser console will use a function then forget it -- I don't actually know why; you can use Codecademy Labs if you want a large practice grounds.)

Anyway, if you're interested in knowing why that worked then read on:

this is a scope accessor that means two different things in JavaScript. If used outside of a function, then it always refers to "the global object" -- which is usually the file it's inside of. The other meaning is inside of a function, where its value depends on how the function was called. If called in JavaScript "strict mode", the value of this is whatever it is when it's used. If it's not defined, then it remains undefined. It can also be set to any value, such as null or 42 or "I am not this". In normal mode, or as I like to call it, "not strict mode", it will refer to the global object.

Does that make sense? :smile:


#9

Yes, I think so, and thank you for your help! :smile:


#10

The problem is the redifinition inside of the function. JavaScript has something that is called hoisting meaning when a variable declaration occurs in a function it is treated as if it would be at the very beginning of the function. So in the end it is case of shadowing where you create 2 variables with the same name and therefore always get the inner variable and not the global one at least if you don't use the this way.