2

Here's the Javascript code:

var _a = _a || [];

Why it uses "||" (logical OR) and "[]" (an empty array) together?

Bakudan
  • 19,134
  • 9
  • 53
  • 73
user748455
  • 385
  • 1
  • 3
  • 10

3 Answers3

5

The expression _a || [] will return _a if it is "truthy", otherwise [] (it is short circuiting, so it only evaluates until one of the operands is 'true' or they have all been evaluated).

This is essentially checking for null. If _a is null or undefined (or false, but that is not likely in this scenario) then it is initialized to an empty array.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • Important to note that the following result in a false 'truthy' check (or, I could just say 'falsy' value): `false`, `null`, `undefined`, `''` (an empty string), `0`, `parseInt({})` (results in `NaN` which is falsy). – Marshall Mar 10 '12 at 00:20
  • @Marshall: Thanks. I am not a JS expert, only toying around with it in my spare time (I'm a systems guy). I specifically used 'truthy' because I thought I may miss one or more cases. Thanks again. – Ed S. Mar 10 '12 at 00:25
  • Well for a systems guy that was a solid answer. A lot of people who use JavaScript don't even understand truthy values ;) – Marshall Mar 10 '12 at 00:33
2

This makes a default state\value. If there is not an _a in the current scope or it is no true or value of any type, it will be created as an empty array. If it exists, it will be reassigned to itself, which is not a very good practice. It is useful in 2 cases:

  1. inside a method ( function ) - another function may return an array or null (for example). If in the method you implicitly needs an array, you assure that _a is an array:

    var _a = _a || [];

  2. passed as parameter - if you need to pass array as an argument. If the argument is null and inside the method you implicitly need an array (this is assigning a default parameter), but it should not override the parameter. It must be assigned to a new variable (I think this is the case because of the underscore):

function doSomething ( a, b, c ) 
{
   ...
   var _a = a || [];
   ...
}
Bakudan
  • 19,134
  • 9
  • 53
  • 73
1

if _a is already defined then use its value, otherwise initialize an empty array

Variant
  • 17,279
  • 4
  • 40
  • 65