I\'m trying to learn javascript and am creating a rudimentary hangman game. However, I keep getting an error when trying to break out of my loop. I can\'t figure it out for the
Break in javascript is only for loops, not if statements so you will get that error message when running your code. Secondly, the while loop becomes an infinite loop as you are not able to stop the alerts to enter anything into the prompt I would rewrite it like this:
var words = [
"javascript",
"monkey",
"amazing",
"pancake"
];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
for (var i = 0; i < word.length; i++) {
answerArray[i] = "_";
}
var remainingLetters = word.length;
while (remainingLetters > 0) {
alert(answerArray.join(" "));
var guess = prompt("Guess a letter, or click Cancel to stop playing.");
if(!guess){
alert('Please enter a letter!')
}
else if(guess.length != 1) {
alert('Please enter a single letter!')
}
else {
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
}
}
}
}
alert(answerArray.join(" "));
alert("Good job! The answer was " + word);