I thought that i--
is a shorthand for i = i - 1
, but I discovered that both evaluate different:
When you do i--
, the value of i
is used and then decremented. But in case of a prefix --1
operator it is different, as in, it will be decremented and then used.
var i = j = 1;
console.log(i--); // still 1
console.log(i); // now 0
console.log(--j) // 0
console.log(j); // again 0
To show you what's going on actually behind when you use pre-fix and post-fix operators, though it is not mainly concerned with the question, but I thought it would be better to know.
What i = i - 1
does is it evaluates as soon as the code is encountered, so i
is actually 0
, you can say it acts similar to pre-fix decrement operator, in this case, but i--
is still 1
when the condition used in while
is evaluated for the first time and then when the second time the while
condition is checked, it is 0
, which is falsey and hence the loop ends.