Let's keep this as simple as possible.
let i = 1
console.log('A', i) // 1
console.log('B', ++i) // 2
console.log('C', i++) // 2
console.log('D', i) // 3
A) Prints the value of I.
B) First i is incremented then the console.log is run with i as it's the new value.
C) Console.log is run with i at its current value, then i will get incremented.
D) Prints the value of i.
In short, if you use the pre-shorthand i.e(++i) I will get updated before the line is executed. If you use the post-shorthand i.e(i++) the current line will run as if I had not been updated yet then i get increased so the next time your interpreter comes across i it will have been increased.
return i++
will return 10.return ++i
would return 11. – Laryngitisi
is being returned and theni
is being incremented. If you write++i
then those two things happen in the opposite order. – Reichi++
an expression is createdint i = i++;
. Let's rewrite this asint j = i++;
so it's easier to explain. This is the post-fix version ofi
, which means incrementi
after settingj = i
. Because, these are primitive integers,i
is deep copied toj
(it's not a shallow copy, with a pointer reference), and thereforej = 10
. Theni
is incremented, soi = i + 1
, and thereforei = 11
. The pre-fix version, will incrementi
before it's copied toj
, and therefore both variables will have the same value (j = 11
,i = 11
). – Shellieshellproof