0

I'm updating a variable from an outer scope in a nested function,
as this is happening during a init function the outer scope isn't the outermost (window) scope;

var init = function() {

  var x = 'old stuff' ;      

        function butClick() {
          x = 'new stuff' ; 
        }
  console.log(x); //  new stuff

  document.querySelector("btn").addEventListener("click", butClick, false);
}
window.addEventListener( 'DOMContentLoaded', init, false);

in order to save it in the init-function scope I'm omitting the var keyword and as expected the new value of the variable bubbles up and updates;

but the result of console.log('x' in window ) is false,
isn't the bubbling supposed to get to the window scope?

maioman
  • 18,154
  • 4
  • 36
  • 42

1 Answers1

2

x is declared within your init function, so no, x within that function (or anything inside it) won't resolve to a global.


Separately, a comment in your question's code :

console.log(x) //  new stuff

...implying that x will be "new stuff" at that point. It won't. You haven't called butClick anywhere, so x will have its original "old stuff" value.

If you did call butClick at some point, it would update the x that's local to init. It wouldn't create or update a global.


Re your update setting butClick as an event handler: The comment suggesting x should be "new stuff" is still wrong. As of the time that console.log line runs, x has the value "old stuff". Later, if someone clicks the button, x will be updated by butClick, but that won't retroactively re-run the console.log line.

But even when called in response to a click, butClick is still updating the x within init, not a global. Variable scope is lexically-determined, not determined by where a function is called from.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • is there a way if I wanted it to become global after first click? – maioman Jan 29 '15 at 12:34
  • @maioman: In the browser environment, you can always create globals by assigning to properties on the global object, which you can reference via its property `window`. So: `window.x = "some value";` creates or updates a global `x` variable. – T.J. Crowder Jan 29 '15 at 12:35