Reputation: 8240
The following JavaScript code should have given output of 32 but the answer is 16. How?
5 + 1 = 6;
6 + 5 = 11;
11 * 2 = 22;
22 + 10 = 32; (should have been answer as per me)
var x = 5;
x = (x++, alpha(x), x*2, x+10);
function alpha(x){
return x+5;
}
console.log(x);
Upvotes: 1
Views: 213
Reputation: 95375
This line doesn't do what you think it does.
x = (x++, alpha(x), x*2, x+10);
Of the four expressions, only one does anything to x
: x++
increments x
(from 5 to 6 in this case). The other expressions are just values sitting there doing nothing. It's exactly the same as if you'd written this:
x = (x++, 11, 12, 16)
(Because the x++
turns x into 6, alpha(x)
returns 6+5=11, x*2 is 6*2 which is 12, and x+10 is 6+10 which is 16.)
So you're assigning a list – not an array – to a single variable. What happens in that case? It gets the last value in the list, and the other values are thrown away. In this case, the last value is 16, so x
is set to 16.
If you wanted to do all that math to x
you would have to actually assign all the values back to x
along the way:
x++
x = x + 5
x = x * 2
x = x + 10
Or else combine all the operations into one expression:
x = ((x+1)+5)*2+10
Upvotes: 2
Reputation: 371138
The alpha(x)
function is pure, without side-effects, and since it's not the last term of the comma operator, it doesn't do anything: you may as well remove it completely. The same can be said for the x * 2
part. So, your code is equivalent to
var x = 5;
x = (x++, x+10);
console.log(x);
x++
increments x
by one, so x
goes from 5 to 6. Then x + 10
evaluates to 16.
With the comma operator, the whole expression resolves to the value on the right, after the final ,
. Another way of looking at it:
var x = 5;
x = (x++, alpha(x), x*2, x+10);
function alpha(x){
return x+5;
}
console.log(x);
is equivalent to
var x = 5;
// comma operator translation starts here
x++; // Increments x; now x is 6
alpha(x); // Unused expression, doesn't do anything
x * 2; // Unused expression, doesn't do anything
x = x+10; // Adds 10 to x, assigns result to x; x is now 16
// comma operator translation ends here
function alpha(x){
return x+5;
}
console.log(x);
Upvotes: 2