Search code examples
javascriptvarscopingoperator-precedencehoisting

Javascript: z = z || [] throws an error when not using VAR - why?


Out of just intellectual curiosity, why does javascript accept

var z = z || [];

to initialize z (as z may defined initially)

but without var, it throws an error (in global space)

z = z || [];

(if z is previously undefined)

In the global space you are not required to use VAR though I get it might be bad practice.

Before you say this is a duplicate of questions like

What is the purpose of the var keyword and when to use it (or omit it)?

Note the declaration that "If you're in the global scope then there's no difference."

Obviously that's not 100% true, given my working example.

Is this a quirk or is there legitimate logic?


adding a summary of the answer as I've learned it:

Thanks to Tim (see below) the key to my misunderstanding was not realizing this (fundamental of javascript)

var z; does absolutely nothing if z already exists

That's how this expression seems to have it both ways, if you incorrect assume that "var z" always initializes.

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.

This is an excellent article on this kind of scoping and hoisting issue in Javascript: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Many thanks to minitech and everyone else who contributed too!


Solution

  • z = z || [] will throw in any scope (global or not) where there is no z in the scope chain. The reason for this is that the expression first attempts to retrieve the value of an existing variable called z on the right hand side, which is an error when none exists.

    The reason why var z = z || [] does not throw an error is that the variable z is created (if it does not already exist) before the expression is executed, an effect commonly known as hoisting.

    On the other hand, assigning a value to an unresolved identifier (e.g. z = 2) will work without error in any scope (except in ECMAScript 5 strict mode, which forbids it and throws). If the identifier cannot be resolved, it will be added as a property of the final object in the scope chain, which is the global object, hence giving the appearance of creating a global variable.