Global variable undefined in function
<p>I am trying to assign the global variables mouseX, mouseY to an event listener inside a function. When I try to use the variables inside another function, they come back undefined. </p>

<p>I know it's probably a problem with the scope of the variables being assigned to, but have not been able to figure it out, and any simple test code I write doesn't reproduce the problem.</p>

<p>What is causing this?</p>

<p>javascript:</p>

<pre><code>var mouseX, mouseY;

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var bars = [];
for(var i = 0; i &lt; 30; i++)
  bars[i] = new Bar(ctx, 100+i*10, canvas.height, 5, 150);

for(var i = 0; i &lt; bars.length; i++){
  bars[i].checkMouse(); 
  bars[i].display(); 
}

function Bar(ct, x, y, w, h){

  this.x = x;
  this.y = y; 
  this.w = w;
  this.h = h;
  this.y -= this.h;

  this.display = function() {
    ct.rect(this.x, this.y, this.w, this.h);
    ct.fill();
  }  
  this.checkMouse = function() { 
    //if(mouseX &gt;= this.x &amp;&amp; mouseX &lt;= this.x + this.w){
    //this.y = mouseY; this.h = height-mouseY; 
    console.log(mouseX);  //////mouseX is undefined?
    //} 
  }  
}  

function getMouse(event) {
  mouseX = event.offsetX;
  mouseY = event.offsetY;
  var coords = "mouseX: " + mouseX + ", mouseY: " + mouseY;
  document.getElementById('display').innerHTML = coords;
}
</code></pre>

<p>HTML:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;style type="text/css"&gt;
    canvas{
        background-color: #e6e6e6;
        position:relative;
    }   
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id="display"&gt;&amp;nbsp&lt;/div&gt;
&lt;canvas onmousemove="getMouse(event)" id="myCanvas" width="500"      height="200"&gt;
&lt;script src="myscript.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>