Defining variable with multiple values in parentheses uses 2nd value

505 views Asked by At

Right so my question is:

var x = (val1,val2);

sets the value of x to val2;

Why?

1

There are 1 answers

1
T.J. Crowder On BEST ANSWER

Because that's how the comma operator works: It evalutes both its operands, and the result of the expression is the value of the second one.

Note that this is very different from what you'd have if you didn't have the parentheses there:

// Differs *significantly* from your example:
var x = val1, val2;

Without the parens, you wouldn't be using the comma operator at all, you'd be using the comma as part of the declaration list of the var statement, which has different semantics — specifically, that x gets the value of val1 and you have a declaration for val2, which isn't initialized in that code.

But again, that's a different thing entirely.