Please explain why this code displays the number 13?

var i = 5; i = ++i + ++i; console.log(i); // 13 

2 answers 2

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

  • +1 perfectly explained, anyone who will try to deal with this issue has the opportunity to read the information already chewed. - LFC
  • The first option is obvious, the second one seems confusing. Probably in order to avoid such confusion, it is advisable to always use ++ i whenever possible? - Beast Winterwolf
  • I do not agree. Both the first and second obvious. Just with practice, you understand where what option you need. Everything depends on the situation. Although frankly, when I taught all this, it was at this moment that I had problems. - LFC
  • one
    @VladSpirin just often people use the usual version of ++i (in the same cycles), and rarely in complex expressions. Therefore, even experienced developers at this point may stick) - Suvitruf
  • one
    @BeastWinterwolf is important to understand the concept. This is the same as with theorems in geometry. If you understand the principle, then you can output / calculate it yourself. - Suvitruf

That's right. First, the first i ++ is executed, then the second one. Only then it develops.