Reputation: 93
I have this simple code on the JavaScript.
var a = 10;
var b = 20;
a=a+b-(b=a);
document.write("a = " + a + "</br> b = " + b);
Can somebody explain me, how did these variables change the values and how is the assignment operator works in this case ? I think, that on the first step the variable b is rewrote by number from a: (b=a).
Upvotes: 0
Views: 339
Reputation: 664548
It's evaluated outside-in, from left to right, as usually.
The assignment expression returns the assigned value.
a = a + b - (b = a); // a=10 b=20
a = 10 + b -( b = a); // a=10 b=20
a = 10 + 20 - (b = a); // a=10 b=20
a = 30 - (b = a); // a=10 b=20
a = 30 - (b = 10); // a=10 b=20
a = 30 - (10); // a=10 b=10
a = 30 - 10; // a=10 b=10
a = 20; // a=10 b=10
20; // a=20 b=10
Upvotes: 2
Reputation: 2090
Simple explanations below.
1 . We are assigning our initial values:
var a = 10;
var b = 20;
2 . Here we're saying a is equal to 10+20 - (10)
. Therefore a
is now equal to 20
and b
is equal to 10
as it was assigned to be a
before we assigned a
's new value.
a=a+b-(b=a);
3 . Result:
var a = 10;
var b = 20;
a = a + b - (b = a);
console.log("a = " + a); // a = 20
console.log("b = " + b); // b = 10
Upvotes: 1
Reputation: 21
Well, let's look closely at this: a = a + b - (b = a);
Let's replace variables with values a = (10 + 20) - (10)
This is because B == 20 until redefined at the end of the expression.
Upvotes: 0