0

I have inherited a project where it looks like there are a lot of variables polluting the global scope and I would like to find all of those. What is the best way to find user introduced global variables? I want to exclude the properties on the window object that are on there by default and just filter down to the ones that have been introduced by our code. Is there a tool or IDE plugin that would allow me to identify these easily? Thanks

2
  • I think jslint warns about variables that aren't declared local. It might produce false positives for standard window properties, but it shouldn't be hard to skip over them.
    – Barmar
    Commented Nov 22, 2016 at 21:37
  • Here are a couple posts on SO post1 post2 Commented Nov 22, 2016 at 21:39

3 Answers 3

6

compare the Keys in your window-object with the keys of an "empty" window-object:

(function(){
    var iframe = document.createElement('iframe');
    iframe.src = "about:blank";
    document.body.appendChild(iframe);

    var windowVars = Object.keys(iframe.contentWindow);
    var globalVars = Object.keys(window).filter(key => !windowVars.includes(key));

    console.log("global Vars:", globalVars);
    document.body.removeChild(iframe);
})();

Now you have to search your code to find the line where they're declared.

1

Getting a Window Object Example: https://jsfiddle.net/noevgh4u/

comparison of Objects example: https://jsfiddle.net/noevgh4u/1/

The most practical way I could think of would be to open up a blank page in the browser of your choice, write out an object based on that windows properties.

document.body.append("var obj = {");
for(prop of Object.keys(window)) {
document.body.append(prop +": null");
};
document.body.append("}");

In the example copy that object from the text on the page.

Paste it into the application you're checking for globals.

Create a new object using

var newObj;
for(prop of Object.keys(window)) {
newObj[prop] = null;
};

so that in the application you now have Obj containing a blank windows keys and newObj containing your applications keys.

Then compare the two using a method such as Deep comparison of objects/arrays

or something like:

function filterKeys(a, b) {
var firstKeys = Object.keys(a);
var secondKeys = Object.keys(b);
var missingKeys = firstKeys.filter(val => !secondKeys.includes(val));
return missingKeys;
}
var createdVarsAndFuncs = filterKeys(obj, newobj);

I created an example of this in jsFiddle https://jsfiddle.net/noevgh4u/1/

-1

Try this...

for(var stuff in window) { 
  if(window.hasOwnProperty(stuff)) console.log(stuff); 
}

This will list all the functions and variables on the page, might not be super useful but might give you some more info.

If you open Chrome dev tools you can try it out. Create a variable var life = 42 and you will see it listed after executing the above for loop.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.