Clean JavaScript code does not leak into the global variable scope. That's why we use strange looking stuff like (function() { var a = 'I am local'; })();
to execute code in a local scope. Inside such scopes, we can declare and use variables without conflict.
Since you often don't get a warning when using undeclared variables, I wrote an 140byt.es snippet to detect leaking variables. The idea is very simple and works in Opera and Firefox. Does not work in Internet Explorer.
Due to a bug in Firefox I had to add a try-catch block. Accessing or even checking the type of window.sessionStorage
causes a "not supported" exception. It works fine without this in all other browsers. Another bug is that Firefox returns a getInterface
method in the second call that was not there in the first call. I did not found out why this happens or how to prevent it. This is why I check for native functions. And (of course) there are problems in Internet Explorer. It does not store global variables in the window
object so the function can't display anything. Replacing window
with this
does not help since it refers to the same object.
Using a zero-length string as a property name is remarkable but also feels strange. Does the ECMAScript specification allow this? I don't think so. However, according to my tests suite it works in all browsers with a single exception: While Internet Explorer (tested with 7, 8 and 9) does allow
myObject['']
on user defined functions and objects, it causes a TypeError exception on native objects likewindow
.Fun thing is, this does not matter since the function doesn't work in Internet Explorer anyway. What I think about is using the remaining 5 bytes to re-add the "Leak:" message.