art with code

2011-03-31

Detecting new globals in JavaScript

JavaScript has this annoying little feature where if you forget the 'var' keyword when assigning to a variable, it creates a new global. This has a tendency to cause some veeery interesting bugs. So. It would be nice to detect those new globals. And I happen to have just the thing for that.

Paste this snippet to your webpage (preferably after creating all the globals you intended to create):
<script type="text/javascript">
if (true /* MONITOR_GLOBALS */) {
(function(){
var globals = {};
var startGlobals = [];
for (var j in window) {
globals[j] = true;
startGlobals.push(j);
}
if (false /* PRINT_INITIAL_GLOBALS */)
console.log("Initial globals: "+startGlobals.sort().join(', '));
setInterval(function() {
var newGlobals = [];
for (var j in window) {
if (!globals[j]) {
globals[j] = true;
newGlobals.push(j);
}
}
if (newGlobals.length > 0)
console.log("NEW GLOBALS: "+newGlobals.sort().join(', '));
}, 1000);
})();
}
</script>

Now whenever a script creates a new global, you get a notification in your JS console. Hopefully sparing you from some agonizing hours of debugging.

Blog Archive