adik
adik

Reputation: 3

An assignment operator inside an assignment operator

'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

  1. console.log(+apples + (apples = +bananas + 3));

  2. console.log(+apples + (apples = 4 + 3));

  3. console.log(+apples + (apples = 7)); //the variable 'apples' is going to be 7

  4. console.log(+apples + 7); //'apples' now equals to 7

  5. console.log(7 + 7);

  6. console.log(14)

  7. 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?

  1. console.log((+apples) + ((apples = (+bananas) + (3)))); //since parentheses now have equal precedence(order), actions are done from left to right

  2. console.log(3 + (apples = 4 + 3));

  3. console.log(3 + (apples = 7)); //the variable 'apples' is going to be 7

  4. console.log(3 + 7); //'apples' now equals to 7

  5. console.log(3 + 7);

  6. console.log(10)

  7. 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

Answers (1)

Yousaf
Yousaf

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:

  1. Coerce the value of apples to a number

    3 + (apples = +bananas + 3)
    
  2. Coerce the value of bananas to a number

    3 + (apples = 4 + 3)
    
  3. Add 4 + 3 and assign the result of addition to apples

    3 + (apples = 7)
    
  4. (apples = 7) - value of this expression is 7

    3 + 7
    

Final result = 10.

Upvotes: 1

Related Questions