Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does this do in js "xin || {}"? [duplicate]

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

like image 997
Huangism Avatar asked Dec 21 '22 06:12

Huangism


2 Answers

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.

like image 162
gion_13 Avatar answered Jan 03 '23 13:01

gion_13


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 : {};
like image 36
Samuel Liew Avatar answered Jan 03 '23 13:01

Samuel Liew