What does this do in js "xin || {}"?

Possible duplicate:
What is var x = x || {};

I have these lines in js, it's simple, I'm sure, but I'm not sure what the last part does - (xin || {})

 var xin = (function (name) {return name;}(xin || {})); 

as I understand it, xin is an object constructor, so now I can create an xin object. Just not too sure what xin || {} does xin || {} xin || {} . Can someone enlighten me please thanks

+4
source share
6 answers
 xin || {} 

matches with:

 xin ? xin : {}; 

or in longer form:

 if(xin) { return xin; } else { return {}; } 

EDIT: See related duplicate question . jAndy does it beautifully:

|| is a logical OR .

Expression

 var x = x OR {}; 

should become more obvious.

If x has a false value (for example, null , undefined , 0 , "" ), we assign x an empty object {} , otherwise just save the current value. The long version will look like

 var x = x ? x : {}; 
+2
source

which assigns the value of xin name argument if it is not false (or undefined or null) or a new object ( {} );

example:

 var name = xin || {}; 

this translates to:

 if(xin) var name = xin; else name = {}; 

In javascript, you can use conditional statements ( || and && ) to create expressions. Here is 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(); 

In any case, this is for demonstration purposes only, you should not use large nested expressions built with conditional operators, because they are very unreadable (therefore it is very difficult to maintain).

This type of expression is often used during initialization when you do not want to overwrite a specific value if it already exists. A good example is using a namespace in multiple js files. Using this method ( var namespace = namespace || {}; ), you can use the same namespace in all files without overwriting it.

+4
source

It computes xin if xin is true, otherwise a new object is used.

+2
source
 a || b 

Operator OR || shorted. This means that if a true, then the value of a || b a || b true and therefore does not evaluate b . It returns a , which is true. If a not true, then it returns b , that is, in this case, if b is false, the expression is false and true if b is true. So xin || {} xin || {} returns xin if xin true, otherwise it returns an empty object {} .

+1
source

It:

 var xin = (function (name) {return name;}(xin || {})); 

identical to this:

 var xin = xin || {}; 

What can be repeated:

 var xin = xin ? xin : {}; 

Simplify further:

 if(!xin) xin = {} 
+1
source

If there is no xin object, it chases the new one, so it passes the new (or existing) xin to the function.

This is a command for artificial namespaces.

+1
source

Source: https://habr.com/ru/post/1382309/


All Articles