What is the difference between i++ and ++i in JavaScript?
i++
- known as post-increment
- it first returns the original value of
ithen increments it by 1
for example:
let i = 1, j;
j = i++;
console.log(i, j); //2 1
First, the value of i is assigned to j then i is incremented by 1. Hence, i is 2 and j is 1.
++i
- known as pre-increment
- it first increments the value of
iby 1 then returns it.
for example:
let i = 1, j;
j = ++i;
console.log(i, j); //2 2
first, the value of i is incremented by 1 and then assigned to j. Hence, i is 2 and so is j.