Here's the Javascript code:
var _a = _a || [];
Why it uses "||" (logical OR) and "[]" (an empty array) together?
Here's the Javascript code:
var _a = _a || [];
Why it uses "||" (logical OR) and "[]" (an empty array) together?
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.
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:
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 || [];
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 || []; ... }
if _a
is already defined then use its value, otherwise initialize an empty array