Why is the global variable not being changed in certain circumstances in a function if you don't declare it with var or it's not an argument?
<p>ECMAScript is pretty straightforward about <code>var</code>. If you don't use <code>var</code> inside a function to declare a variable you assign to you assign to the global scope. This happens because of the way chain scoping works. The executing environment looks for the identifier in the local scope and then moves up until it reaches the global scope. If hasn't found a declaration for the the identifier and it's not identified as an argument the variable is created in the global scope.</p>

<p>For example local scope:</p>

<pre><code>var car = 'Blue';

function change_color () {
  var car = 'Red';
} 
change_color();
console.log(car); //logs 'Blue' as car is in the local scope of the function.
</code></pre>

<p>When <code>car</code> is not found in the local scope:</p>

<pre><code>var car = 'Blue';
function change_color () {
  car = 'Red';
}
change_color();
console.log(car); 
//logs 'Red' as car is not in the local scope and the global variable is used.
</code></pre>

<p>Now apparently there's an exception to this rule that I wasn't aware of and don't understand (<strong>notice the function name</strong>):</p>

<pre><code>var car = 'Blue';
(function car () {
 car = 'Red';
})();
console.log(car); //Logs 'Blue'????
</code></pre>

<p>Can anyone explain this please? I don't see where this is explained in the ECMASpec. Tested in Chrome 8 and Firefox 3.6</p>
