11/11 Creating all three at once


#1

Going back to the lesson I decided to combine all three into one for fun, however the output is unexpected.

for (var i = 0; i > 20; i++){
do{
console.log("Testing");
}
while(i < 10);
}
console.log(i)

I expected the for loop to count 1-20 and "Testing" to print 10 times. Underneath I expect 1-20 to be printed out. However when run all I get is a printout of "0". Lesson still passed but I'm not sure why this result is coming out.


#2
for (var i = 0; i > 20; i++){
do{
console.log("Testing");
}
while(i < 10);
}
console.log(i)

Had the above for statement executed you would have had an infinite loop. Fortunately, the statement has a mistake in the conditional expression, i > 20. A variable cannot have a value of zero and be greater than 20 at the same time. The loop never executes.

for (var i = 0; i < 20; i++) { ... }

Consider the first iteration, with i = 0.

do {
    console.log("Testing");
} while (i < 10);

This loop will never end. i will remain less than 10 for all of infinity or until the browser times out. There is no change in the state of i inside the loop. We could solve this with another control variable that takes its value from i

for (var j, i = 0; i < 20; i++) {
    j = i;
    do {
        console.log("Testing", i, j);
    } while (--j > 0);
}
console.log(i);  // 20

#3

Whoops! I thought I avoided the infinite loop. I think I understand your answer now. The initial code I made never got started so i remained at the initial value (0) and that was all that was printed (I knew changing the i = 0 in the for loop changed the print out).

Your code makes more sense although I'm struggling with using --j in the while loop. This is something new to me, so I'll look into it and continue learning. I think it's the same as j-- as switching it in the code doesn't seem to effect the result, either way I've not used it in this context.

Thanks for the reply! Getting there slowly but surely!


#4

Study further before putting this in the rear view mirror. What is --j after all? Learn about it; don't just take my answers at face value, however well intentioned. Seek.