I thought that i--
is a shorthand for i = i - 1
, but I discovered that both evaluate different:
i--
is not the same as i=i-1
, when used in a loop.
i--
will be evaluated after the condition, but before the loop contents are run, whereas i=i-1
will be evaluated before the condition, so will evaluate to false.
I guess in that respect --i
is more similar to i=i-1
, as it is also evaluated prior to the condition.
You can think of
while (i--) {...}
As being equivalent to
while (i = i - 1, i + 1) {...}
The i--
will be evaluated only after the loop condition is evaluated but before the statements within the loop. This is the decrement postfix operator. That means that initially the evaluation of the condition in the loop condition would be true
. This will fire the execution of the statements in the loop's body. When the statements in the loop's body will be executed, since the i
had be decremented by one, it would be equal to 0. Hence the evaluation of the loop condition would be false
and the statements in the loop's body will not be executed again.
You should use --i
as the pre-decrement operator.
See the docs here
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.