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 Create the Loop – One Solution

Kirok James
seal-mask
.a{fill-rule:evenodd;}techdegree
Kirok James
Full Stack JavaScript Techdegree Student 876 Points

number of attempts and guess the right number

How would I terminate the loop either if the user guess the right number or user had already 10 attempts to show message "You tried 10 times" and when right number message "you guessed the number"

Do I need to use conditional statement for this and where exactly should I place it?

Thank you for answer

2 Answers

Steven Parker
Steven Parker
231,275 Points

There are a number of ways to do this, but one simple one is to add a counter variable and then increment and test it in the loop:

// before the loop:
let counter = 0;

// inside the loop:
  if (++counter > 10) {
    alert("You tried 10 times");
    break;
  }

For detailed help with placement, you'd need to show your code, preferably by sharing a snapshot of your workspace.

josephweiss2
josephweiss2
8,698 Points

Hi Kirok James, Here is a Loop example.

for(var i = 0; i <= 10; i++) {
  if(i===10) {
    alert("You tried 10 times");
  } else if(right answer) {
       alert("you guessed the number");
       break;
    }
}

this should answer your question, let me know if it helped you or you need more help