0

I found this expression on one web site.

var _g = _g || [];

What doest it mean?

Alex
  • 2,091
  • 6
  • 31
  • 49

2 Answers2

5

it simply prevent the _g value to be null or undefined, if the _g on the right side is null or undefined, _g will be assigned to an empty array.

it is like :

if(!_g) {
  _g = [];
}
Mathieu Bertin
  • 1,634
  • 11
  • 11
  • Not just `null` or `undefined` but also others like `0`, `NaN`, empty string. See https://developer.mozilla.org/en-US/docs/Glossary/Falsy – dreyescat Nov 04 '14 at 12:53
  • Yes sure but in this case the value expected is an array so there is few chances for having a 0 or NaN but you are right – Mathieu Bertin Nov 04 '14 at 12:54
  • @MathieuBertin Then if the expected value is an array, why use this guard? – dreyescat Nov 04 '14 at 12:55
  • because your array can not be set so undefined... You are right on the case that if _g equals NaN or 0 _g will be assigned to an empty array but I think that the developer wanted to prevent the undefined or null case that's why I didn't mention it. – Mathieu Bertin Nov 04 '14 at 12:57
3

set _g equal to _g, but if _g is undefined, set it to an empty array;

infrared
  • 102
  • 2
  • 5