Javascript beginner: logical or empty brackets

Here is the Javascript code:

var _a = _a || [];

Why does he use "||" (logical OR) and "[]" (empty array) together?

+1
source share
3 answers

The expression _a || []will return _aif it is “true”, otherwise [](it is a short circuit, therefore it evaluates only one of the operands “true” or all of them were evaluated),

This is essentially a null check. If _ait is null or undefined (or false, but this is unlikely in this case), then it is initialized with an empty array.

+4
source

\default . _a true , . , , . :

  • () - (). , , , _a :

    var _a = _a || [];

  • - . , ( ), . ( , - ):

function doSomething ( a, b, c ) 
{
   ...
   var _a = a || [];
   ...
}
+1

if _aalready defined, use its value, otherwise initialize an empty array

0
source

All Articles