user429620
user429620

Reputation:

var a, b, c = {}

I thought the syntax:

var a, b, c = {};

would mean that the three variables are separate, not references to the same {}.

Is this because {} is an object and this is the standard behavior?

So if I do:

var a, b, c = 0;

the three would indeed be separate and not references?

Thanks, Wesley

Upvotes: 1

Views: 14805

Answers (6)

Michael Taufen
Michael Taufen

Reputation: 1704

Yes, the three would be separate.

The comma operator evaluates the left operand, then evaluates the right operand, then returns the value of the right operand.

This makes for a nice way to declare a bunch of variables in a row if you just rely on the evaluation of the operands and don't do anything with the returned value.

var i = 0, j = 1, k = 2; is basically equivalent to var i = 0; var j = 1; var k = 2

Another use for this is to squeeze multiple operations onto one line without using ;, like in a for loop with multiple loop variables:

for(var x=0,y=5; x < y; x++,y--)

Notice how both x++ and y-- can be performed on the same line.

Upvotes: 0

zatatatata
zatatatata

Reputation: 4821

Using coma to separate variables enables to define multiple variables in the same scope more compactly. In your sample, though, only c = {} and a and b would be undefined. You could use similar construct to assign something like

var a = {first: 'foo'}, 
    b = {second: 'bar'}, 
    c = {third: 'foobar'};

which would be equal to

var a = {first: 'foo'}, b = {second: 'bar'}, c = {third: 'foobar'};

and also to

var a = {first: 'foo'};
var b = {second: 'bar'};
var c = {third: 'foobar'};

And each one would only reference to their respective object. Using comas is basically just a visual aspect.

Upvotes: 0

Flambino
Flambino

Reputation: 18773

They shouldn't be the same, no. Only c will be assigned the value.

a and b would just be declared, but not initialized to anything (they'd be undefined). c would, as the only one of them, be initialized to {}

Perhaps it's clearer when written on several lines:

var a,      // no assignment
    b,      // no assignment
    c = {}; // assign {} to c

Upvotes: 12

Joseph Marikle
Joseph Marikle

Reputation: 78550

var a, b, c = {}; only defines the last var namely c. it's similar to the syntax var a = {}, b = [], c = 0;

it's just short hand for declaring multiple vars.

Upvotes: 0

Rob Fox
Rob Fox

Reputation: 5571

In the examples you only define the last element

a and b are undefined

Upvotes: 1

Kaken Bok
Kaken Bok

Reputation: 3395

var a, b, c = {};

This will declare 3 variables (a, b, c) but define only 1 variable (c).

var a, b, c = 0;

This will declare 3 variables (a, b, c) but define only 1 variable (c).

Upvotes: 4

Related Questions