Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unlike many C-style languages, JavaScript supports block syntax but does not support block scope, so the following may not run as you would expect:</p> <pre><code>var foo = 'bar'; { var foo = 'baz'; } console.log(foo); // 'baz' </code></pre> <p>This is also evident in other JavaScript constructs that support blocks like <code>if</code>:</p> <pre><code>var foo = 'bar'; if (true) { var foo = 'baz'; } console.log(foo); // 'baz' </code></pre> <p>Moreover, as Bergi pointed out, your <code>i</code> counters for <code>for</code>s will override each other because a <code>for</code> will not create a new scope.</p> <p>Crockford considers JavaScript's lack of block scope an <a href="http://rads.stackoverflow.com/amzn/click/0596517742" rel="nofollow">"Awful Part"</a> of the language. Instead, JavaScript has <a href="http://en.wikipedia.org/wiki/Lexical_scoping#Lexical_scoping_and_dynamic_scoping" rel="nofollow">lexical scoping</a>, so only functions will create a new scope:</p> <pre><code>var foo = 'bar'; (function() { var foo = 'baz'; console.log(foo); // 'baz' }()); console.log(foo); // 'bar' </code></pre> <p>Every function in JavaScript has access to the variables in the function that contains it; inner has access to outer, but not vice versa. In the case of the above example, the <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" rel="nofollow">IIFE</a> (immediately-invoked function expression) has access to the <code>foo = 'bar';</code> defined in the global scope, but instead we choose to override <code>foo</code> with a local <code>var</code> declaration and set it equal to <code>'baz'</code>.</p> <p>Bonus Point: Shog9 found that <code>with</code> can simulate block scope with an object literal like so:</p> <pre><code>var foo = 'bar'; with ({foo: 'baz'}) { console.log(foo); // 'baz' } console.log(foo); // 'bar' </code></pre> <p>Crockford <a href="http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/" rel="nofollow">discourages <code>with</code></a> due to its ambiguity, but if you really desire block scope, I see no harm in the <code>with</code> workaround.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload