Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Complete the Loop

Johnny Jones
Johnny Jones
10,162 Points

"while ( counter < 11 )". Why is it not 10?

I was able to pass the test eventually but I honestly do not know why it is "while ( counter < 11 )". Why is it not 10?

var counter = 1;
while ( counter < 11 ) {
    document.write("<p>Now in loop #" + counter + "</p>");
    counter += 1;

2 Answers

The idea of the loop is to output the numbers 1 ... through 10. The counter is being incremented each time. When counter is equal to 10, it checks the statement

(counter < 11)

and it is true because 10 < 11, then it outputs the number ten. After you increment the counter variable to 11 it checks again

(counter < 11)

this is false because 11 is not less than 11 and the while loop ends. You end up with 10 print statements 1 through 10. Now another way to write this would be

 (counter <= 10)

This way the loop will continue as long as the counter is less than or equal to 10.

I hope this helps!

Johnny Jones
Johnny Jones
10,162 Points

You explained that very well, thanks for the help!

If you change the counter to start at 0 (var counter = 0). It can be 10 like you say instead of 11.