Reputation: 3
'use strict';
let apples = '3';
let bananas = '4';
console.log(+apples + (apples = +bananas + 3));
The output is 10, unexpectedly. I thought it would be 14, and the compiler would think something like this
console.log(+apples + (apples = +bananas + 3));
console.log(+apples + (apples = 4 + 3));
console.log(+apples + (apples = 7)); //the variable 'apples' is going to be 7
console.log(+apples + 7); //'apples' now equals to 7
console.log(7 + 7);
console.log(14)
14
But on the step 4, 'apples' apparently equals to 3. Why isn't the output 14?
update: Can it be that there are parentheses around each operand, which are automatically added even though not directly written?
console.log((+apples) + ((apples = (+bananas) + (3)))); //since parentheses now have equal precedence(order), actions are done from left to right
console.log(3 + (apples = 4 + 3));
console.log(3 + (apples = 7)); //the variable 'apples' is going to be 7
console.log(3 + 7); //'apples' now equals to 7
console.log(3 + 7);
console.log(10)
10
That would, I think, logically explain why there is 10 instead of 14.
Sorry for clumsy code. I was just doing some practice after reading about operators in js.
Upvotes: 0
Views: 61
Reputation: 29281
On step 4, value of apples
isn't 7 because the expression in your code example is evaluated from left to right.
So the following expression:
+apples + (apples = +bananas + 3)
is evaluated as:
Coerce the value of apples
to a number
3 + (apples = +bananas + 3)
Coerce the value of bananas
to a number
3 + (apples = 4 + 3)
Add 4 + 3 and assign the result of addition to apples
3 + (apples = 7)
(apples = 7)
- value of this expression is 7
3 + 7
Final result = 10.
Upvotes: 1