JavaScript global variables & self-invoking anonymous functions
<p>So I've been reading through <a href="http://rads.stackoverflow.com/amzn/click/0596517742" rel="nofollow">Javascript - The Good Parts</a> and one thing that Crockford points out is the use weakness of global variables in Javascript, in such a way that if your product is expanded in some manner, and it relies on a 'global' variable it could be inadvertently set.</p>

<p>That's all good and fine and I understand the pros/cons of protecting variables, in other manners such as closures as well. However, I was doing some thinking, and wrapping code in a function like so:</p>

<pre><code>(function () {
    var x = 'meh';
})();
(function () {
    alert(typeof x); // undefined
})();
</code></pre>

<p>gives it variable scope, which thereby prevents cross contamination of variables. I'm not sure if there's a blatant downside to this approach though and wondered if the community had any input, or if I'm just overthinking things and ignoring the main point. </p>
