Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does global variable stay undefined even after assigning value to it in a local scope in javascript

Tags:

javascript

My understanding of the closure property is that every variable inside in a function scope has access to all the variables in the parent scope(s) the function is in,

So considering this definition I don't understand the behavior of my code below:

var mouseX, mouseY;

window.onload = function() {

    this.addEventListener('mousemove', function() {
        mouseX = event.clientX;
        mouseY = event.clientY
    }); // mouseX and mouseY are defined

    petObj = new Pets();


   }

function Pets(){
document.getElementById('imageList').addEventListener('mouseenter',function()
                                       {
                                       console.log(mouseX)} //undefined mouse X!!!
                                       }

I accept the assignation of mouseX inside the anonymous function for mousemove event listener to reference the global variable declared outside the function. But as you can see it stays undefined outside the scope of the anonymous function

like image 251
Snedden27 Avatar asked Jan 18 '26 03:01

Snedden27


1 Answers

You're logging the value of "mouseX" inside the "load" handler that sets up the event handler. No events have happened yet, so the variable is still undefined.

The variables are available, and if you put a console.log() call inside the event handler, or somewhere else such that the code will run after some "mousemove" events have happened, you'll see the values being updated.

like image 182
Pointy Avatar answered Jan 19 '26 18:01

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!