开发者

What does var x = x || {} ; [duplicate]

This question already has answers here: What does "var FOO = FOO || {}&q开发者_StackOverflow社区uot; (assign a variable or an empty object to that variable) mean in Javascript? (8 answers) Closed 8 years ago.

what does the following code do in java script:

var x = x || {};


|| 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 x is undefined (or null, or any other false value), it becomes an empty object.


One should never write "var x = x || {};" per se.

The only circumstance where this is not identical to "var x = {};" is when x was previously initialized in the same scope. That is immoral. Note:

function() {
  x = {foo:"bar"};
  var x = x || {};
}

Is the same as, merely more confusing than,

function() {
  var x = {foo:"bar"};
  x = x || {};
}

In neither case is there any reference to the value of the symbol "x" in the global scope.

This expression is a confused variant of the legitimate lazy property initialization idiom:

function( foo ) { 
  foo.x = foo.x || {};
  foo.x.y = "something";
}


Assign x to a new empty object if it is null (undefined, false) or keep it's existing value if not null.


unless x is defined or assigned a value it will take empty object as default value..

that is,

for example
x = 10
var x = x || {};

output must be

10

if x value not assigned. the output value must be,

undefined


if var x is defined then it will be that defined value. Else it will be empty object like [object Object]

For example, in the following code block, x will be 10:

var x = 10;
x = x || {}

However, if:

var x = x || {};

then x will be [object Object]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜