Pre-increment vs. post-increment

Pre-increment vs. post-increment
0.0 0


Hello, can anybody please help me to solve this question. As I understood X++ increments after the assignment, but ++X does it before the assignment. However, both - x and y - result in counting until 9 on the webpage and both count until 10 in the console.
Why doesn’t the webpage show the number 10 for Y, because here the pre-increment is used.

Thanks in advance!!

<!DOCTYPE html>

<p id="demo"></p>

var text = "";
var text2 = "";
var x;
var y;
for (x=0; x < 10; x++)  { 
 text += "x is " + x ;}
 for (y=0; y<10; ++y) { 
 text2 += "and y is " +  y; } 
console.log (x, y);
  document.getElementById("demo").innerHTML =text + text2;



A brief extract from here

When a for loop executes, the following occurs:

* The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
* The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. If the condition expression is omitted entirely, the condition is assumed to be true.
* The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements.
* If present, the update expression incrementExpression is executed.
Control returns to step 2.

It means the increment operation is made at the end of the block code before to re-enter the loop. It doesn’t matter if you use post-increment or pre-increment here( my opinion, hope it makes sense ^^).

Hope it helps,


Thanks a lot. In that way there is no difference between the two versions of increment. So, the additional use for the pre-increment is to assign the original value of a variable to another variable and then count 1 to the variable.
It gives no difference in the loop. Thanks again!