Checking for global scope leak

Last night I got a wild hair and wanted to write a bit of code for fun. Basically I wanted to see what variables were added to the global scope by different libs and bits of code. Basically you can run this and it will tell you if you have accidentally left off a var or added something to the global namspace in some other way. It is rather simple, it does add a var to the global, but I remove that at the end so you don’t see funny results.

To run it, simply replace the:

<script src="jquery-2.1.3.js" type="text/javascript"></script>

with whichever files you wish to check. The code is pretty simple:


<html><head>
	   <title>What's New</title>
    </head>
<body>

	<script type="text/javascript">
		_cleanWindow = Object.getOwnPropertyNames(window);
	</script>

	<script src="jquery-2.1.3.js" type="text/javascript"></script>

	<script type="text/javascript">
		(function(){
			var _modifiedWindow = Object.getOwnPropertyNames(window);
			var _newShit = {};
			var i = j = 0;
			var output = '<\/ br>';


			for(i = 0; i <= _modifiedWindow.length; i++) {
				for(j = 0; j <= _cleanWindow.length; j++) {
					if(_cleanWindow[j] === _modifiedWindow[i]) {
						break;
					}

					if(j === _cleanWindow.length &amp;&amp; _modifiedWindow[i] !== '_cleanWindow') {
						_newShit[_modifiedWindow[i]] = _modifiedWindow[i];
					}
				}
			}

			for(prop in _newShit) {
				output += prop + ': ' + window[prop] + '<br>';
			}

			document.body.innerHTML += output;

		})();
	</script>

</body></html>

About RTPMatt

I'm a Software Engineer Living in Asheville, NC. I specialize in Front-End development, currently with ReactJS. I also consult on some Vue projects.
This entry was posted in javascript, programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *