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
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
a
and b
are undefined
. What do you mean ?
– slaphappy
Commented
Aug 4, 2011 at 13:01
var a = b = c = {};
– epascarello
Commented
Aug 4, 2011 at 13:03
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
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).
In the examples you only define the last element
a
and b
are undefined
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.
Using a to separate variables enables to define multiple variables in the same scope more pactly. 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 as is basically just a visual aspect.
Yes, the three would be separate.
The ma 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.