Skip to content Skip to sidebar Skip to footer

What Does The "||" Mean In Javascript Array Creation?

I have quite a lot of experience in javascript, but today I came across the piece of code like this for the first time: var _array = _array || []; _array.push(['someItem']); The s

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?"