javascript i++ vs ++i [duplicate]
The difference between i++
and ++i
is the value of the expression.
The value i++
is the value of i
before the increment. The value of ++i
is the value of i
after the increment.
Example:
var i = 42;alert(i++); // shows 42alert(i); // shows 43i = 42;alert(++i); // shows 43alert(i); // shows 43
The i--
and --i
operators works the same way.
++variable
increments the variable, returning the new value.
variable++
increments the variable, but returns the old value.
--variable
decrements the variable, returning the new value.
variable--
decrements the variable, but returns the old value.
For example:
a = 5;b = 5;c = ++a;d = b++;
a
is 6, b
is 6, c
is 6 and d
is 5.
If you're not using the result, the prefix operators work equally to the postfix operators.
I thought for completeness I would add an answer specific to the first of the OP's question:
One of your example shows the i++ / ++i being used in a for loop :
for (i=1; i<=10; i++) { alert(i);}
you will get 1-10 in your alerts no matter which you use. Example:
console.log("i++"); for (i=1; i<=10; i++) { console.log(i); } console.log("++i"); for (i=1; i<=10; ++i) { console.log(i); }
Paste those into a console window and you can see that they both have the same output.