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

Martin Bornman
PLUS
Martin Bornman
Courses Plus Student 12,662 Points

do while loop

What am I doing wrong?? var x = 0; do { console.log('I love JavaScript'); x += 1; } while ( x <= 10)

1 Answer

It seems like your code is unfinished.

Correct Answer

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

The code runs the first time in the do part. Then it adds +1 to the var x. You have to set the while condition to "x <= 9" because the code starts running at x = 0. Here is the number of console logs:

  • x = 0 -> 1. console log
  • x = 1 -> 2. console log
  • x = 2 -> 3. console log
  • x = 3 -> 4. console log
  • x = 4 -> 5. console log
  • x = 5 -> 6. console log
  • x = 6 -> 7. console log
  • x = 7 -> 8. console log
  • x = 8 -> 9. console log
  • x = 9 -> 10. console log

now the loop ends because

...
while(10 <=9)
...

returns false.