Which values does the while loop show?
For every loop iteration, write down which value it outputs and then compare it with the solution.
Both loops alert
the same values, or not?
-
The prefix form
++i
:let i = 0; while (++i < 5) alert( i );
-
The postfix form
i++
let i = 0; while (i++ < 5) alert( i );
The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons.
-
From 1 to 4
let i = 0; while (++i < 5) alert( i );
The first value is
i = 1
, because++i
first incrementsi
and then returns the new value. So the first comparison is1 < 5
and thealert
shows1
.Then follow
2, 3, 4…
– the values show up one after another. The comparison always uses the incremented value, because++
is before the variable.Finally,
i = 4
is incremented to5
, the comparisonwhile(5 < 5)
fails, and the loop stops. So5
is not shown. -
From 1 to 5
let i = 0; while (i++ < 5) alert( i );
The first value is again
i = 1
. The postfix form ofi++
incrementsi
and then returns the old value, so the comparisoni++ < 5
will usei = 0
(contrary to++i < 5
).But the
alert
call is separate. It’s another statement which executes after the increment and the comparison. So it gets the currenti = 1
.Then follow
2, 3, 4…
Let’s stop on
i = 4
. The prefix form++i
would increment it and use5
in the comparison. But here we have the postfix formi++
. So it incrementsi
to5
, but returns the old value. Hence the comparison is actuallywhile(4 < 5)
– true, and the control goes on toalert
.The value
i = 5
is the last one, because on the next stepwhile(5 < 5)
is false.