i++ vs ++i
This one always trips me up. If the ++
increment is after the operand, then
it's called a post increment (i++
). If the ++
is before the operand,
then it's called a pre increment (++i
).
With the post increment, the value gets incremented by one, and returns the original value.
1let i = 22let j = i++34console.log({ i, j })5// { i: 3, j: 2 }
With the pre increment, the value gets incremented by one, and returns the new value.
1let i = 22let j = ++i34console.log({ i, j })5// { i: 3, j: 3 }
They're commonly seen in for-loop
s where it generally doesn't matter which
one is used.
1for (let i = 0; i < 3; i++) {2 console.log(i) // outputs 0, 1, 23}45for (let j = 0; j < 3; ++j) {6 console.log(j) // outputs 0, 1, 27}