Search code examples
javascriptscopelexical-scope

Bubbling scope - Updating var from nested function


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?


Solution

  • 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.