Search code examples
javascriptscopesetintervallocal-variablesjquery-events

Javascript variable scope riddle


I am looking at some of my older code and I can see this, which really confuses me. Code is simplified and located inside a function (object).

$('#element')
.on('mousedown', function(e){

        var mouseX = e.pageX;

        $('body').on('mousemove', function(e){
            mouseX = e.pageX;
        });

        timer = setInterval(function(){
            console.log(mouseX);
        }, 100);
})
.on('mouseup mouseleave', function(){
    $('body').off('mousemove');
});

I needed that mouseX to be up do date when every interval fired, so back then, when my programming understanding was a bit sketchy, I simply thought, great, let's update that variable inside another event (mousemove).

Now looking at it I think - how does that local variable get updated in another scope, that is created independently and furthermore is then successfully used in completely different (interval) scope, that is also created independently?!

The code works(mouseX is correct), and it is not creating a "member" variable in parent function/object.

Can someone enlighten me a bit please.


Solution

  • This is as a result of a concept called "Clousre"

    ...a closure gives you access to an outer function’s scope from an inner function... - MDN.

    The mouseX variable was declared in a function whose scope is top-level to the callBack function given to the mousemove event listener and the setInterval callBack function, because of this, they can both access the mouseX variable.

    You can read more on Closures here.