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.
So many ideas for such a tiny code snippet. That's really cool, thank you all. Let's see:
=1
assignment with the?:
check. @xpansive did it. Good job. The reason why I did not do this is that it makes the array very big, about 100 KB when calling the function first. It will shrink in the second call but I'm not sure if 2 bytes are worth the trouble.d
as a shortcut saves 2 bytes. Accepted.b=''
and adding[b]
was suggested before. But this will displayundefined
instead of an empty dump. If that's not a problem for you, you can save 2 bytes.a.µ
instead ofa.__
is a nice idea (it even haves a meaning). But in UTF-8 encoding this character is 2 bytes. Not exactly a rule but I'm more comfortable if my snippets don't contain high ASCII characters.a[a]
instead ofa.__
is crazy, but works very nicely in all browsers including IE.If you don't care about the problems mentioned you can golf this down to 131 bytes (when using an 8 bit encoding).
I think I will stick with one of these 137 bytes versions.
@azproduction, I'm not sure why but your byte counts are wrong.Corrected.@tsaniel, when I remove the "native" check I get
getInterface
included in the dump when running my test locally in Firefox.