admin管理员组文章数量:1318335
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
2 Answers
Reset to default 8The 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
版权声明:本文标题:javascript array declaration with OR - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742041755a2417578.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论