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 = [];
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).
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 || {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With