Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript: z = z || [] throws an error when not using VAR - why?
    text
    copied!<p>Out of just intellectual curiosity, why does javascript accept </p> <pre><code>var z = z || []; </code></pre> <p>to initialize z (as z may defined initially)</p> <p>but without var, it throws an error (in global space)</p> <pre><code>z = z || []; </code></pre> <p>(if z is previously undefined)</p> <p>In the global space you are not required to use VAR though I get it might be bad practice.</p> <p>Before you say this is a duplicate of questions like</p> <p><a href="https://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript">What is the purpose of the var keyword and when to use it (or omit it)?</a></p> <p>Note the declaration that <strong><em>"If you're in the global scope then there's no difference."</em></strong></p> <p>Obviously that's not 100% true, given my working example.</p> <p>Is this a quirk or is there legitimate logic?</p> <hr> <p>adding a summary of the answer as I've learned it:</p> <p>Thanks to Tim (see below) the key to my misunderstanding was not realizing this (fundamental of javascript) </p> <blockquote> <p>var z; does absolutely nothing if z already exists</p> </blockquote> <p>That's how this expression seems to have it both ways, if you incorrect assume that "var z" always initializes.</p> <p>Starting from the left, "var z" simply makes sure z is defined but does not actually affect any existing value if it already exists. Then on the right, if z already exists, it is used, if not, the variable was just declared (but empty) so it won't be used but will not throw an error.</p> <p>This is an excellent article on this kind of scoping and hoisting issue in Javascript: <a href="http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting" rel="nofollow noreferrer">http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting</a></p> <p>Many thanks to minitech and everyone else who contributed too!</p>
 

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