Вопрос

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!

Это было полезно?

Решение

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.

Другие советы

The effect is correct. var will always declare its "operands" right away, whereas when you don't declare it, your script attempts to use an undefined variable and throws an error.

If you're in global scope, you can assign to a nonexistent variable and it will have the same effect as declaring it, bad practice as that may be. Of course, in your case, it's undefined. This being said, although it may be out of intellectual curiosity, you would never write

var z = z || [];

because it makes no sense to do so. Rather, you might do:

if(!window.z) {
    window.z = [];
}

. In fact, when I declare things in the global scope (which is never ;)) I use window.something instead because it makes my intent more clear.

You may assign to an undeclared variable z = 123; however you may not attempt to read one which is what z = z || [] does.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top