Possible Duplicate:
What does “options = options || {}” mean in Javascript?
I stumbled upon this line, and can't seem to figure out what it means
var G = G || {};
Any ideas?
Possible Duplicate:
What does “options = options || {}” mean in Javascript?
I stumbled upon this line, and can't seem to figure out what it means
var G = G || {};
Any ideas?
G = G, and if G does not exist, create it as an empty object.
G is G or a new object if G is not defined "falsy".
If G
is currently any "falsey" value, then the object literal will be assigned to G
.
The "falsey" values are...
undefined
null
''
NaN
false
0
The operator being used is the logical OR operator.
The way it works is that it evaluates its left operand first. If that operand has a "truthy" value (any non-falsey value), it returns it, and doesn't evaluate (short-circuits) the second operand.
If the left operand was "falsey", then it returns its right operand, irrespective of its value.
Example where G
is falsey...
// v--- Evaluate G. The value of G is the "falsey" value undefined...
var G = G || {};
// ^--- ...so evaluate and return the right hand operand.
Example where G
is truthy...
G = 123;
// v--- Evaluate G. The value of G is a "truthy" value 123...
var G = G || {};
// ^--- ...so return 123, and do not evaluate the right hand operand.