May 19, 2011

How many global variables are there?

We all know global variables in JavaScript are bad.

If you declare a bunch of variables/functions in the global namespace they become properties of the global object, in the browser that would be the window object.

So the other day I was thinking of a way to find out how many of them were in a page. So I came up with this script that you can run to find out:
(function (window) {
    var document = window.document,
        hasOwnProperty = Object.prototype.hasOwnProperty,
        globals = [],

    for (prop in window) {
        !, prop) && globals.push('@');

    div = document.getElementById('abc-js-globals') ||
        document.createElement('div'); = || 'abc-js-globals';
    div.innerHTML = '<h2>Global Variables:</h2><ul>'
        + globals.join('') + '</ul>';


You can paste that in the Firebug/Inspector console and a list of the globals will show up at the end of the page.
The names that start with @ mean they are properties inherited from the prototype chain.

UPDATE: I changed the code to be slightly faster (I think). I guess that makes it version 1.1.

No comments:

Post a Comment