What Does The "||" Mean In Javascript Array Creation?
Solution 1:
It checks if _array
is defined, otherwise, it assigns an array to it. Basically a "Use existing or assign new" scenario.
The second line can then run safely since _array
is (presumably) an existing array, or a newly created array, courtesy of the first line.
Solution 2:
It means or
. In this case you can read it as get _array variable or create new empty array if _array doesn't exist
.
Solution 3:
This |
character is called a pipe.
When used in a pair ||
it represents a logical OR. (It's used widely in other languages too).
It will try to do the left most expression first, and if that expression evaluates to false, it will do the right most expression.
In our case, it tests if the variable _array
exists, if it does it basically assigns _array
to _array
. If it does not exist yet, it will initialize _array
as an empty array ([]
).
It could also be rewritten as a ternary operator like:
var _array = _array ? _array : [];
Post a Comment for "What Does The "||" Mean In Javascript Array Creation?"