tags:

views:

202

answers:

5

what does the following code do in java script:

var x = x || {};
+6  A: 

If x is undefined (or null, or any other false value), it becomes an empty object.

Gabe
+1  A: 

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

Darin Dimitrov
+10  A: 

|| 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 : {};
jAndy
excellent answer. i am a c programmer and this didnt make any sense.
jakoh
If this didn't make any sense for you, then you might also watch out for `!!value` which returns a boolean representing the truthfulness of `value`, very handy at times.
Ivo Wetzel
Your long version is incorrect: consider the case when x has previously defined and is set to `null`. `var x = x || {};` will redefine x to an object, whereas `var x = (typeof x !== 'undefined') ? x : {};` will not. The paragraph preceding it is correct though.
Tim Down
@Tim: true, I forgot about the `typeof null === 'object'` enigma.
jAndy
+1  A: 

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
Senthil Kumar Bhaskaran
A: 

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

e.g. var x = 10; x = x || {}

then it will be 10

var x = x || {};

then it will be [object Object]

Anil