title: javascript variable undefined despite having been defined
body: <p>I'm trying to get the mouse's position on an HTML5 canvas using this function:</p>
  
  <pre><code>function getMousePos(canvas, evt) {
      var rect = canvas.getBoundingClientRect();
      return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
      };
  }
  </code></pre>
  
  <p>The function is called through an event listener (listening to the mousemove event) attached to the window DOM object.</p>
  
  <p>I declared the initial values of mousePos as 0,0 in an object like so:</p>
  
  <pre><code>var engine = {
      canvas: document.getElementById('main'),
      mousePos: {x:0,y:0},
      ...
  }
  </code></pre>
  
  <p>Whenever I move the mouse outside of the canvas and reload the page, the console reports:</p>
  
  <pre><code>Uncaught ReferenceError: mousePos is not defined
  </code></pre>
  
  <p>Since the window.mousemove event has not fired yet, the variable is undefined. But to me, it seems that before I use the variable for the first time, it is defined properly. Despite that, why do I still receive this error?</p>
  
  <p>The rest of my code (including HTML): <a href="https://pastebin.com/03FZ2Q3L" rel="nofollow noreferrer">https://pastebin.com/03FZ2Q3L</a></p>
  
  <p>Thank you in advance.</p>