 Consider following code snippet:
for( var i=0; i<7; i+=2 )
{
if( ++i==5 ) break;
else continue;
}
console.log( i++ );
What will be printed to the console?
Explanation
If statement will not be executed, so i variable will reach 9 and the loop will stop. Then i++ returns i value (9) before the increment operation was applied.
1. var i=0 // i=0
2. ++i==5 // i=1 -> 1==5 -> false
//Note: prefix incerement (++i) evaluates before equality (==) operator
// unlike, postfix increment(i++) evaluates after:   e.g.  var i=0; then i++==1 -> false, but ++i==1 -> true
3. i+=2 // i=3
4. i<7 // 3<7 -> true
5. ++i==5 // i=4 -> 4==5 -> false
6. i+=2 // i=6
7.  i<7 // 6<7 -> true
8. ++i==5 // i=7 -> 7==5 -> false
9. i+=2 // i=9
10. i<7 // 9<7 -> false
11.  alert( i++ ); // here will be alerted 9 because it is postfix operator

Oh, it is a great improvement of the question, @docahrens! Cool, thanks)

2016 Jun 15, 7:22:27 PM

your explanation is too brief. you should show how it ended up as 9 by going through the order of increments. question would probably be better is it did not come out to 9, because many would guess the right answer by accident assuming that because 9 was the limit of the for loop (which your explanation seems to imply), but it is only a coincidence that the increments totaled to 9. If you change the limit to 7 like so: for(var i=0; i<7; i+=2 ), the question would be better, because they if they guess it is the limit they would be wrong, it is still 9.

2016 Jun 12, 2:31:20 PM

Слідкуй за CodeGalaxy Зареєструйся Зараз
або Підпишись на майбутні тести