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! While you're at it, check out some resources Treehouse students have shared here.

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 Review while loops, do...while loops, and Loop Conditions

Karl Taylor
Karl Taylor
4,043 Points

What am I missing? console.log('I Love Javascript'); - 10 times?

Am I missing something here because I did the exact same code into my own browser and it worked fine...

Question:

Finish the code in this loop's condition, so that 'I love JavaScript' is printed to the console 10 times:

var x = 0;

do {

  console.log('I love JavaScript');

  x += 1; 

} while ( x <= 10 ) // 10 being the answer

Apparently this is wrong - I've tested it locally and it seems to be correct.

3 Answers

Byron Stine
Byron Stine
4,877 Points

Remember a do loop will run once before it is evaluated with the while condition at the end of the loop. Since x=0 then the console.log('I love JavaScript') will run before x is increased by one. The condition says to run until x <= 10. This means it will 11 times. If you change the condition to x < 10 or x <= 9. Then it will only run 10 times.

Cosimo Scarpa
Cosimo Scarpa
14,047 Points

The loop is run once when the script start. So if you need arrive at 10, consider to run only other 9 time. This is the correct answer anyway.

var x = 0;
do {
  console.log('I love JavaScript');
  x += 1; 
} while ( x <=  9 )