Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.