0

Good day, was reading a JavaScript script library and come across this

var g = g || {};

What does this means?

WyHowe
  • 69
  • 1
  • 11

4 Answers4

2

This is a way to ensure g is actually initialized as an object. It is the same as:

if(!g) g = {};

The || is an OR. The second operand will be returned only if the first one evaluates to false.

Derlin
  • 9,572
  • 2
  • 32
  • 53
  • Thanks. nice explanation. Didn't know you can do that. will mark as correct once 10 min pass.. – WyHowe Jan 26 '16 at 08:00
2

It means, that if g is 0/null/undefined, the g will be defined as an empty object.

The common way:

function foo(g) {
    // If the initial g does not defined, null or 0
    if(!g) {
      // Define g as an empty object
      g = {}
    }
}
Sergey Rura
  • 234
  • 2
  • 3
0

JavaScript returns the first argument if true, otherwise the second one. This is equivalent to an OR.

So in your example, if g is not set, it is set to an empty object.

William
  • 741
  • 4
  • 9
0

Following description is taken from this page.

expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand can be converted to true; if both can be converted to false, returns false.

In your case, if g has a falsy value (false/null/undefined/0/NaN/''/(document.all)[1]), then g will be set with {}

guysigner
  • 2,822
  • 1
  • 19
  • 23