4

i found a javascript line below while studing a project :

var array = array || [];    // <--- confusion here (what does || mean)

can anyone tell me why someone declared the array like above instead of :
var array = [];

UPDATE : after having the answers i figured out more readable way to do the above :

if(array == undefined) 
    var array = [];
2
  • I'm pretty sure there should be no difference here - array must be undefined, because when the expression is evaluated, array has just been declared. Commented Aug 24, 2013 at 12:57
  • 1
    @Eric No : array may already have been declared. This is frequent in multi-files constructs. Commented Aug 24, 2013 at 13:02

2 Answers 2

8

The difference with simply var array = []; is that if there already is an existing value, this value isn't replaced with [].

It works because

this is equivalent to

var array; // does nothing if array is already declared in the same scope
if (!array) array = [];

This kind of construct is frequent when you have a modular code and don't want to impose an order of import : you may have many files starting with the same line :

var myModule = myModule || {};

Here's an example : SpaceBullet source code (look at the first lines of the js files).

Sign up to request clarification or add additional context in comments.

13 Comments

Seems more like a error, should have been array = array || []; without the var prefix. Since its basically redclaring the same variable name.
it depends. There's no problem with an additional var.
so u mean i can also do something like if(array == undefined) var array = []; ?
To be less risky, I would always use window. instead of var (assuming this is global scope) to ensure it validates, lints, compiles, etc.
@AshokDamani in fact you're mostly right. It's better to test with undefined but the code is, strictly speaking, more equivalent to the code I show (that is it would also replace array if its value was "" for example).
|
3

This means: If there is a value or array is initialized, assign it to the variable, otherwise, initialize this variable as an empty array.

You will see similar declarations with {}

var someObject = anObject || {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.