Search code examples
javascriptarithmetic-expressions

Can somebody explain how javascript Arithmetic expressions work?


Let's evaluate this code for swapping two variables :

var a = 5, b = 3; 
a = ( a -( b = ( a = a+b ) - b ) );

I was expecting that new value of a should be 3 and value of b should be 5. But I got values as a = 0 and b = 5;

I went and read the EcmaScript Arithmetic expression and found that this will be evaluated from left-to-right. ( but not completely clear ).

So I tried this one

var a = 5, b = 3; 
a = ( ( b = ( a = a+b ) - b ) - a );

Now I got a = -3 and b = 5. Can somebody explain me why this is happening like this ?


Solution

  • As you said, the expression is evaluated from left to right, meaning the first time a is encountered, its value is still 5. This comes down to:

    var a = 5, b = 3; 
    a = ( a -( b = ( a = a+b ) - b ) );
    a = 5 - (b = (a=(5+3)) - b);
    a = 5 - (b = 8 - b);
    a = 5 - 5; AND b = 5
    

    In the second one, the a value is evaluated after the assignment because it is on the right

    var a = 5, b = 3;
    a = ( ( b = ( a = a+b ) - b ) - a );
    a = ( ( b = 8 - b ) - a ); AND a = 8
    a = ( 5 - 8 ); AND a = 8; AND b = 5;
    a = - 3;
    

    It all comes down to the order of the evaluation of the operands.

    Typically in the first case, a is evaluated to 5, then b = ( a = a+b ) - b is evaluated, and only during this evaluation the value of a changes, but is not backported.

    In the second example, ( b = ( a = a+b ) - b ) is evaluated first, changing the a value to 8, then a is evaluated, and is found to be 8

    A more trivial example is :

    var a = 5
    a = a + (a = 2)
    // a = 7
    

    a is evaluated to 5, then (a = 2) is evaluated to 2 and a is set to 2, then 5+2 is evaluated and a is set to 7.

    On the other hand :

    var a = 5
    a = (a = 2) + a
    // a = 4
    

    (a = 2) is evaluated to 2 and a is set to 2, then a is evaluated to 2, then 2+2 is evaluated and a is set to 4