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
Without seeing the rest of the code to understand the scope I would assume that you are using break incorrectly. Instead you should be using return.
Break is used inside loops (for, while, for in, switch etc). Where as return is used to return from functions, if blocks and can either return a value or not.
if (guess === null) {
return;
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);
Put the break inside the loop
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 === null) {
break;
} 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);