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!
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

Nurbek Ismailov
2,068 Pointsfor 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
19,201 PointsI 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');
}
};

fbriygig
15,370 PointsApart 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
2,068 Pointsthank 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?

fbriygig
15,370 PointsThere'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');
}
}
Julian Gutierrez
19,201 PointsJulian Gutierrez
19,201 Points*Markdown edited