I'm not sure a count of global variables is, of itself, a useful indicator of anything. You should do some analysis to work out which are created by code, which are host specific and which are related to the environment (e.g. DOM).
In a browser, the window object is a synonym for the global object, hosts are allowed to add properties to it (e.g. window.name) as well as define properties on its prototype (if it has one).
Also, all element IDs are created as properties of window (you can blame Microsoft and IE for that), so if there are lots of element IDs then there'll be lots of global properties.
Anyway, below are two ways to count the own enumerable properties of the global (window) object. It uses an IIFE so it doesn't create any properties itself.
// Create 3 global properties
var x, y, z;
(function(global) {
// for..in with hasOwnProperty check
var count = 0;
for (var prop in global) {
if (global.hasOwnProperty(prop)) {
count++;
}
}
console.log('for..in count: ' + count +
// Direct count using Object.keys
'\nObject.keys : ' + Object.keys(global).length);
// Pass global (window in a browser) object to function
}(this));
So an approach to testing for code-created variables in a browser may be to:
- Count the number of global properties in an "empty" document, that should be the default host-defined set
- Count the total number of global properties in the suspect document
- Count the number of elements in the document with an ID
So the number of code-created globals should be the result of item 2 - (item 1 + item 3).
You can count the elements with an ID something like:
var allEls = document.getElementsByTagName('*');
var idCount = 0;
for (var i=0, iLen=allEls.length; i<iLen; i++) {
if (allEls[i].id != '') {
++idCount;
}
}
or:
[].filter.call(document.getElementsByTagName('*'), function(el) {
return el.id != '';
}).length;