Why "1" printed at the end of this Do-While loop?



I create a for loop and a do-while loop in this exercise. However, at the end of the output "1" prints out and I don't understand way. The code runs fine, and I am not getting an error, just not sure where that "1" is coming from. Here is the code:

for (i = 10; i > 0; i--) {
    console.log("say " + i);

var n = 10;
do {
    console.log("I do!");
} while (n !== 0);

the output is this:

say 10
say 9
say 8
say 7
say 6
say 5
say 4
say 3
say 2
say 1
I do!
I do!
I do!
I do!
I do!
I do!
I do!
I do!
I do!
I do!

Baffles me, but I am curious to know why!


Ok, i just occurred to me that it may have something to do with the codeacademy console assesses you code. For example, whenever you run code the console prints a 'true' or 'false', even if there is no 'console.log' statements in the code. And since '1' === true, then it might be something to do with that.


You are on the right track... It is the console doing this, not your code, and not codecademy. The last value assigned in the loop is 1 so it is still in the buffer when the program terminates. The console gives this as a response.

Let the last executed 'command' be console.log() and the buffer won't echo. In other words, increment n before the log out.

A note about loop control conditions...

In your case this works, but, it comes with a gotcha, theoretically. What happens if n never equals zero? The loop never ends.

Safer, and a better practice to always use an inequality so that a range of values will satisfy the conditional.

while ( n > 0 )

This way if the value of n is outside of the valid range, it immediately fails.


Thank you for that. Makes sense about that last #1 printing to console.

Okeydoke, I will adjust my while conditions to using the greater or lesser than symbols from here forth.