Please explain why this code displays the number 13?
var i = 5; i = ++i + ++i; console.log(i); // 13 Please explain why this code displays the number 13?
var i = 5; i = ++i + ++i; console.log(i); // 13 ++i is a pre-increment. It is calculated before using the variable.
That is, the first ++i calculated, in i now 6 , the expression is now 6 + (++6) . Then we calculated the second ++i , in i now 7 . Then they laid down 6 + 7 , got 13 .
On the other hand, for example, if you take the post-increment i++ .
After i = i++ + i++; i will be 11 , because Post-increment is calculated after using the variable.
Ie, it was substituted into the expression, the first i++ calculated, in i now 6 , the expression was 5 + (6++) . Then the second i++ , i was 6, it was substituted, it became 5 + 6 , after which i became equal to 7 . Add 5 + 6 , got 11 .
++i (in the same cycles), and rarely in complex expressions. Therefore, even experienced developers at this point may stick) - Suvitruf ♦That's right. First, the first i ++ is executed, then the second one. Only then it develops.
Source: https://ru.stackoverflow.com/questions/870565/
All Articles