Javascript increment operation order evaluation

I know what the prefix / prefix increment / decrement operators do. And in javascript this doesn't seem to be different.

So far, I can easily guess the outcome of this line:

var foo = 10; console.log(foo, ++foo, foo, foo++, foo); 
// output: 10 11 11 11 12

how operators are ++displayed in separate expressions.

This gets a little complicated as these operators appear in a single expression:

var foo = 10; console.log(foo, ++foo + foo++, foo);
// output[1]: 10 22 12
// Nothing unexpected assuming LTR evaluation

var foo = 10; console.log(foo, foo++ + ++foo, foo);
// output[2]: 10 22 12
// What? Ordering is now different but we have the same output.
// Maybe value of foo is evaluated lazily...

var foo = 10; console.log(foo, foo + ++foo, foo);
// output[3]: 10 21 11
// What?! So first 'foo' is evaluated before the increment?

and my question is: how did Javascript (V8 in this case when I tested them in Chrome) end up evaluating the add expression in the second and third examples differently?

Why value fooends differently than foo++. Should postfix be ++incremented after an expression and evaluated only fooinside the expression?

+6
3

:

foo++ + ++foo

:

foo++ 
    addition_lhs = foo  // addition_lhs == 10
    foo += 1            // foo == 11
++foo 
    foo += 1            // foo == 12
    addition_rhs = foo  // addition_rhs == 12

addition_lhs + addition_rhs == 10 + 12 == 22

foo + ++foo:

foo 
    addition_lhs = foo  // addition_lhs == 10
++foo 
    foo += 1            // foo == 11
    addition_rhs = foo  // addition_rhs == 11

addition_lhs + addition_rhs == 10 + 11 == 21

, , .

, , - , JavaScript (LHS) , , (RHS).

, , , :

alert(1) + alert(2) + (function () { throw Error(); })() + alert(3)
+7

, foo++, "": , , . ++foo, : , . ++ +, "" (foo++)+(++foo)

+2

var foo = 10; console.log(foo, ++ foo + foo ++, foo);

++foo + foo++
   11 + 11

foo 11, foo , - 11, 22, foo .

var foo = 10; console.log(foo, foo ++ + ++ foo, foo);

foo++ + ++foo
10    +    12

, ++ foo, foo ++

var foo = 10; console.log(foo, foo + ++ foo, foo);

foo + ++foo
10  +   11

foo , foo, 10 + 11

Basically it all depends on what the current value of foo is when you add them together.

+1
source

Source: https://habr.com/ru/post/1618630/


All Articles