Can someone explain why the alert still shows 5 under postfix? I understand prefix identifies the last iteration to be falsy, but with postfix, it will still return i as 5.
// Prefix Code:
let i = 0;
while (++i < 5) {
alert(i);
}
// Postfix code:
let i = 0;
while (i++ < 5) {
alert(i);
}
There are different outputs. With prefix, the output is 1, 2, 3, 4
With postfix, the output is 1, 2, 3, 4, 5
I’m unable to understand why the postfix output will return 5.
2
Answers
The prefix operator
++i
increments then outputs the variable, and the postfix operatori++
outputs then increments the variable.For the prefix code,
++i
outputs the value ofi
itself after incrementing, soi
never reaches5
.It outputs
1, 2, 3, 4
. The first one is1
becausei
gets incremented from0
.For the postfix code,
i++
outputs a value of the incrementedi
smaller by one, so even ifi
had reached5
byi++
ing, it actually outputs4
. Because of the outputted4
being smaller than5
, the final statement gets executed.The value of
i
by the last statement execution is5
, so5
gets printed at last.By that, the output is
1, 2, 3, 4, 5
.Then the
i++
will print5
fori = 6
so the execution gets stopped.Postfix example:
Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment
So in the postfix the comparison in the
while
condition is done with 4 but the value in thatalert
is 5