What does var x = x || {} ; [duplicate]
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]
精彩评论