0

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 sedond line is obious, but I don't have any idea about the first line - what is the || in there, why isn't that var _array = []; instead?

I've done some research on google but I didn't get any clue what does this strange construction really do. Can you please enlighten me?

  • What is that strange construction?
  • What is the difference between that and simple array declaration?
  • Why would anyone use that? My eyes hurt when I look at that line of code...

EDIT:

I am perfectly aware that || is a logical OR (and of the way how logical OR works) but I have never seen it used that way - in variable declaring.

Kamil T
  • 2,232
  • 1
  • 19
  • 26

3 Answers3

4

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.

Joseph
  • 117,725
  • 30
  • 181
  • 234
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.

Elon Than
  • 9,603
  • 4
  • 27
  • 37
1

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 : [];
Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58