While loop with nested statement if does not loop javascript

advertisements

I don't understand why, but my loop won't complete. I am supposed to make a guessing game using javascript but the loop won't actually loop. It just takes an answer, displays the appropriate window and stops. Regardless of the answer. Here is the code :

<!DOCTYPE >
<html>
<head>
<title>Welcome To The JS Guessing Game</title>
</head>
<script> 

//Initialize the variables that will be needed.
var target;
var target_index;
var guess_input;
var guesses=0;
var finished=false;
var guesses=0;
var colors = ["blue", "cyan", "gold", "green", "magenta", "orange", "red", "white", "yellow"];

function do_game() {
    var random_number = (Math.random()*colors.length);
    var random_number=Math.floor(random_number);
    target=colors[random_number];
    alert(target);
    while (!finished){
        guess_input=prompt("I am thinking of a color in the list below. Can you guess which color?"+"\n\n"+ colors.join() );
        guesses++;
        if (guess_input!=target){
            alert("no")
            return true;
        }
        alert("yes!!")
        return false;
    }
}
</script>
<body onload="do_game()">
</body>
</html>

Now I really don't understand what i am doing wrong, and the console flags up no error in any browser :/ I would really appreciate the help!

Cheers,

David


The issue is that you're breaking out of the while loop when an incorrect answer is entered and you run the code:

if (guess_input!=target){
    alert("no")
    return true;
}

Rather than returning a value, consider using a continue statement.

if (guess_input!=target){
    alert("no")
    continue;
}

This will jump to the next iteration of the loop, staying within the loop but not executing the alert("yes!!"). Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

(And as per comments on your question, you don't really need the finished variable, just using while(true) should be sufficient.)