There is a difference between pre-increment (++x
) and post-increment (x++
).
A pre-increment operator is used to increment the value of a variable before using it in a expression. In the pre-increment, value is first incremented and then used inside the expression. Let's say we have:
a = ++x;
Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in the expression. This is equivalent with:
x = x + 1;
a = x;
A post-increment operator is used to increment the value of variable after executing expression completely in which post increment is used. In the Post-Increment, value is first used in a expression and then incremented. Let's say we have:
a = x++;
Here, suppose the value of ‘x’ is 10 then value of variable ‘a’ will be 10 because old value of ‘x’ is used. This is equivalent with:
a = x;
x = x + 1;
You can read more on the interned about this (for example, here or here).
Cheers!
// Post-increment example
console.log("post-increment examples");
let x = 10;
a = x++;
console.log(x, a);
x = 10;
a = x;
x = x + 1;
console.log(x, a);
// Pre-increment example
console.log("pre-increment examples");
x = 10;
a = ++x;
console.log(x, a);
x = 10;
x = x + 1;
a = x;
console.log(x, a);