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.

4 comments:

Crusader said...

Neat!

TiTi said...

This is interesting, but somewhat weird to do that on the client-side, once the script as been coded.
What I mean is that kind of script should not end up in production, it's just an helper for development.

You should check out ajaxmin.exe, thee ajax analyzer/minifier by microsoft.
In the analyze mode, it gives you this information at the very end of the report, see "Undefined Global References:". Ex:

Undefined Global References:
jQuery [Variable] at Line 13, Column 4
console [Variable] at Line 50, Column 6

Ilmari Heikkinen said...

Good point! I agree that this belongs somewhere upstream in the dev process.

One guy said that NetBeans can be configured to highlight globals in red. So if you take that and add build-time detection, you should have your own code covered.

Anonymous said...

Or you could run your script through JSLint/JSHint and it will tell you.

Blog Archive