While hangi deerleri gsterir?
Her dng iin ekranda gsterilecek deerler nelerdir? Bu deerleri yazn ve sonra cevap ile karlatrn.
Her iki dngde de alert ayn deerleri mi gsterir?
Both loops alert same values or not?
-
nden eklemeli
++i:let i = 0; while (++i < 5) alert( i ); -
Sonradan ekelemeli 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++ifirst incrementsiand then returns the new value. So the first comparison is1 < 5and thealertshows1.Then follow
2, 3, 4the values show up one after another. The comparison always uses the incremented value, because++is before the variable.Finally,
i = 4is incremented to5, the comparisonwhile(5 < 5)fails, and the loop stops. So5is 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++incrementsiand then returns the old value, so the comparisoni++ < 5will usei = 0(contrary to++i < 5).But the
alertcall is separate. Its another statement which executes after the increment and the comparison. So it gets the currenti = 1.Then follow
2, 3, 4Lets stop on
i = 4. The prefix form++iwould increment it and use5in the comparison. But here we have the postfix formi++. So it incrementsito5, but returns the old value. Hence the comparison is actuallywhile(4 < 5)true, and the control goes on toalert.The value
i = 5is the last one, because on the next stepwhile(5 < 5)is false.