Possible Duplicate:
What does var x = x || {} ;
I have this lines in js, it is simple i am sure but i am not sure what the last part does - (xin || {})
var xin = (function (name) {return name;}(xin || {}));
as I understand it, xin is a object constructor so now I can create object of xin. Just not too sure what the xin || {}
does. Can someone enlighten me please, thanks
that attributes to the name
argument the value of the variable xin
if it is not false (or undefined or null) or a new object ({}
);
example :
var name = xin || {};
this is translated into :
if(xin)
var name = xin;
else
name = {};
In javascript you can use the conditional operators (||
and &&
) to create expressions. Here's an example :
typeof f === 'function' && ((arguments.length == 0 && f()) || f.apply({},arguments)) || g();
this expression can be translated into the following :
if(typeof f === 'function')
{
if(arguments.length == 0)
f();
else
f.apply({},arguments);
}
else
g();
Anyway, this is just for demo purposes only, you shouldn't use large nested expressions built with conditional operators because it's highly unreadable (therefore very hard to maintain).
This kind of expression is often used on initializations , when you do not want to overwrite a certain value if it already exists. An good example would be the usage of a namespace within multiple js files. Using this technique (var namespace = namespace || {};
) you can share the same namespace in all the files without overwriting it.
xin || {}
is the same as:
xin ? xin : {};
or, in longer form:
if(xin) {
return xin;
}
else {
return {};
}
EDIT: See linked duplicate question. jAndy puts it nicely:
||
is the logical OR
.
The expression
var x = x OR {};
should become more obvious then.
If x
has a falsy value (like null
, undefined
, 0
, ""
), we assign x
an empty object {}
, otherwise just keep the current value. The long version of this would look like
var x = x ? x : {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With