admin管理员组

文章数量:1318156

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 = [];

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 = [];
Share Improve this question edited Aug 24, 2013 at 13:21 AKD asked Aug 24, 2013 at 12:53 AKDAKD 3,9644 gold badges35 silver badges51 bronze badges 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. – Eric Commented Aug 24, 2013 at 12:57
  • 1 @Eric No : array may already have been declared. This is frequent in multi-files constructs. – Denys Séguret Commented Aug 24, 2013 at 13:02
Add a ment  | 

2 Answers 2

Reset to default 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

  • 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 || {};

本文标签: javascript array declaration with ORStack Overflow