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

Nurbek Ismailov
Nurbek Ismailov
2,068 Points

for loop question for guessing game: even if i answer correctly, loop doesn't exit

for loop question for guessing game: even if i answer correctly, loop keeps running asking me me questions. How can i fix my code so it exit the loop after the 1st correct answer?

for (x= 0; x < 3; x++) { {var guess = prompt ("what is my name?")}
    if (guess.toLowerCase () === 'nick')
    document.write ("Good job guessing my name");
    else {
    alert('good try, better luck next time');
    }
};

3 Answers

Julian Gutierrez
Julian Gutierrez
19,201 Points

I looks like you have a few misplaced curly braces and some missing around your if statement

for (var x = 0; x < 3; x++) {
  var guess = prompt('what is my name?')

  if (guess.toLowerCase() === 'nick'){
    document.write('Good job guessing my name');
  } else {
    alert('good try, better luck next time');
  }
};

Apart from the curly braces, you need a way to exit the loop after a correct guess. The break keyword can do this:

for (var x = 0; x < 3; x++) {
  var guess = prompt('what is my name?')

  if (guess.toLowerCase() === 'nick'){
    document.write('Good job guessing my name');
    break;
  } else {
    alert('good try, better luck next time');
  }
}
Nurbek Ismailov
Nurbek Ismailov
2,068 Points

thank you guys, it fixed it. However, i wanted the alert {'good try, better luck next time') after 3 failed attempts, any idea how i can do it?

There's probably a neater way to do this but if you refactor your code a little this should work:

for (var x = 0; x < 3; x++) {
  var guess = prompt('what is my name?')

  if (guess.toLowerCase() === 'nick'){
    document.write('Good job guessing my name');
    break;
  } else if (x == 2) {
    alert('good try, better luck next time');
  }
}