for (var i = 0; i < 5; ++i) { alert(i); // 0,1,2,3,4 } for (var i = 0; i < 5; i++) { alert(i); // 0,1,2,3,4 } 

https://jsfiddle.net/z0ugbbwj/

I did not see the difference.

  • in this example, no, there are legends that ++ i is faster (partially true for complex objects). Well, if the expression is more than i ++, then the priority can change the meaning. - pavel
  • @pavel Well, in theory, this is not a legend, because with the postfix increment, the previous value is also memorized there. it is strange that everywhere and everybody have been taught to write his name. - user208916 5:06
  • A good compiler will convert this. - pavel

3 answers 3

In the given example there is no difference. Learn more about the legend that ++i faster.

It is rumored that to execute ++i value in memory increases and then returns. While for i++ , the value in the created temporary variable is first remembered, then the value of the main variable increases and the value of the temporary variable is returned - thus the “costs” of creating a temporary variable increase.

Performance test fails to look because of a temporary jamb on their side.

  • one
    It was the second year of a temporary school .. - Vladimir Gamalyan

In this case, there is no difference, since this expression is executed at the end of the iteration and can be rewritten in this way.

 for (var i = 0; i < 5;) { console.log(i); // 0,1,2,3,4 ++i; } for (var i = 0; i < 5;) { console.log(i); // 0,1,2,3,4 i++; } 

Since this expression is executed separately, and its return value is not used - there is no difference how to change the value of a variable, absolutely similar options:

 i += 1; i = i+1; i = inc(i); ... 

The difference will appear when using the increment in the second block:

 for (var i = 0; ++i < 5;) { console.log(i); // 0,1,2,3,4 } for (var i = 0; i++ < 5;) { console.log(i); // 0,1,2,3,4 } 

    The difference is that ++i increments and then returns the value. i++ returns the value and then increments.