Image

Tracking Down Global Variables

Since JavaScript automatically declares variables global if they aren't formally declared anywhere else, it's really easy to make mistakes by forgetting to declare variables that you intend to be local.

So, I wrote this function, noticeGlobals, that checks every second whether any new globals have appeared. It invokes itself, so all you need to do is include this code in your script.

var noticeGlobals = (function noticeGlobals()
{
  var globals;
  function check()
  {
    for (var i in window)
    {
      // globals[i] is true if the the window property
      // exists and undefined if it doesn't.
      if (globals[i] !== true)
      {
        globals[i] = true;
        alert("Undeclared global: "+i);
      }
    }
  }
  return function()
  {
    globals = new Object();
    for (var i in window)
    {
      globals[i] = true;
    }
    check();
    window.setInterval("noticeGlobals();",1000);
    return check;
  };
})()();


It works in Mozilla. I haven't checked whether it works in IE for Windows. It doesn't work in IE for mac. It works in Safari if it's the last thing in your script.

I'm pretty sure it only works in Mozilla and other Gecko browsers. But as long as you have Mozilla, that's not a problem. This is just a tool for you; you're going to remove it before publishing your script anyway.