meep
meep

Reputation: 334

Node.js - while-loop break error Inside Condition

Hello I'm a new member of stackoverflow as I'm looking for some help. I've currently started learning node.js and began to write some very simple command line programs to get familiar with it etc. However I'm having some trouble. I'm making a game where the program generates a random number between 1 and 10 and the user must guess what the number is within 3 tries. It uses a while loop. Within the while loop it has break statement inside a condition but it is triggering an error and I would really appreciate some help. The chances are I'm either being a bit stupid and missing something or it is (at the moment) simply a bit too difficult at this stage for me as im very new it it. The Error I'm Receiving is:

"
break;
^^^^^^
SyntaxError: Illegal break statement

"

Here is the code

var prompt = require('prompt');
var randomNumber = Math.floor(Math.random() * 10) + 1;
prompt.start();
console.log("Guess The Random Number Between 1 And 10.");
var guesses = 0;
while (guesses < 3) {
    var userGuess = prompt.get(['Guess -> '], function (err, result) {
        if (userGuess == randomNumber) {
            console.log("Correct! Well Done. The Number Was " + randomNumber + 
". You Guessed It In " + guesses + " Trys.");
            break;
        }
        else {
            guesses = guesses + 1;
            console.log("Wrong Number. Guess Again.");
            continue;
        }
    }
})

I have a feeling that it is simpler than I think, but some help would be awesome. Thanks.

Upvotes: 0

Views: 10941

Answers (1)

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18389

You are trying to use break and continue inside prompt.get callback rather than inside the while loop.

To quit execution of the callback, just use return;.

To break the while cycle, you could for example declare a variable before the while loop, add that variable to the while condition` and then adjust the value of that variable inside the callback.

var guesses = 0;
var breakTheLoop = false;

while (guesses < 3 && !breakTheLoop) {
    prompt.get(['Guess -> '], function (err, result) {
        if (wannaBreak) {
            return breakTheLoop = true;
        } else {
            guesses = guesses + 1;
            console.log("Wrong Number. Guess Again.");
            return; // just return instead of continue
        }
    }
}

I would also bet that your prompt.get call will not return the value, but it will be rather accessible in the callback (from result).

Upvotes: 1

Related Questions