Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript array declaration with OR

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 = [];
like image 947
Ashok Damani Avatar asked Nov 06 '25 22:11

Ashok Damani


2 Answers

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

It works because

  • var doesn't declare a new variable if it is already declared in the scope (variable declarations are hoisted)
  • || returns the first non falsy value (for example a defined array)

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).

like image 169
Denys Séguret Avatar answered Nov 08 '25 15:11

Denys Séguret


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 || {};
like image 27
Husein Roncevic Avatar answered Nov 08 '25 13:11

Husein Roncevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!