Search code examples
javascriptglobal-variables

JS: local var X global (window) var


Studying global vars in JS here, I set out to try it and to my surprise this:

var thisVar = "global var";

function showVarLet() {
  var thisVar = "local var";
  console.log("%s   %s", thisVar, window.thisVar);
}
showVarLet();

gives me:

local var
undefined

but the same in the browser console, gives me:

local var
global var

So, what´s with this window object?

EDIT:

I tried to check in the console what would happen if instead of window.thisVar I referenced this.thisVar, my assumption was that I would access the local variable but I keep accessing the global one, why so?


Solution

  • and the code I showed is in a function called global()

    then none of the two thisVars is global, one is a local variable of the global() function, the other one is a local variable of showVarLet(). You cannot access local variables via window..