While loop with nested statement if does not loop javascript


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 :

<title>Welcome To The JS Guessing Game</title>

//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);
    while (!finished){
        guess_input=prompt("I am thinking of a color in the list below. Can you guess which color?"+"\n\n"+ colors.join() );
        if (guess_input!=target){
            return true;
        return false;
<body onload="do_game()">

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!



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){
    return true;

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

if (guess_input!=target){

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.)