Reputation: 749
var a=1;
b=++a*a;
console.log(b);
console.log(a);
the result is 4,2.how the program get this result? in my mind,the result will be 2,2
can anybody tell me how the javascript compiler compile this piece of code and get the result 4,2.
Then the deep question is why these two pieces of code result are the same.
var a=2;
var b=3;
c=(a++)*a;
console.log(c);
var a=2;
var b=3;
c=(a++)*b;
console.log(c);
can anyone explain this one step by step?
Upvotes: 1
Views: 95
Reputation: 176
++a increases the value to 2 before the multiplication. After this, variable "a" will point to value 2 and it will make the multiplication: 2*2.
a++*a wil give you the desired result (2,2)
Upvotes: 0
Reputation: 6463
++
has a higher precedence than *
. Thus b = ++ a * a
is evaluated as b = (++a) * a
.
++a
makes a
equal to 2 and then a
gets muliplied by itself.
On a sidenote, every time you get confused by something like this, find JavaScript's operator precedence table and try to break the equation down by yourself.
Upvotes: 1