0

I'm trying to make it so the program repeatedly accepts input and repeats it back until "exit" is inputted. Right now the loop doesn't run, and I don't know why since the exit variable is set to false. Here's my code:

var read = require("read");
var exit = false;


function OutsideLoop (exit) {

while(exit === false){

        read({prompt: "> "}, function (err, result) {

        console.log("");
        console.log(result);
        console.log("Type in more input or type 'exit' to close the program.");

        if(result === "exit"){
            exit = true;};
        });


};

};


OutsideLoop();

Thanks for the help guys. I have a similar loop working using if/then instead of while, so I rewrote this one along the same lines.

11
  • That is absolutely not how you should prompt. Commented Nov 7, 2013 at 22:55
  • You could say if(!exit)exit = false; in your OutsideLoop function at the very top of your code. Then you won't need to pass the parameter. Commented Nov 7, 2013 at 22:59
  • @PHPglue: No, that would still refer to the same exit. Commented Nov 7, 2013 at 23:00
  • Since there's only one condition to exit the loop, simpler to do while (exit !== true) {do stuff}. Commented Nov 7, 2013 at 23:02
  • Looks like I have to teach you something again @minitech. when @Ber calls OutsideLoop() with no argument it is undefined, therefore my comment is correct. Commented Nov 7, 2013 at 23:02

3 Answers 3

5

You've declared "exit" as a parameter to the function, so the outer declaration has no effect on the logic inside the function. You don't pass anything to the function when you call it, so "exit" is undefined and the === test fails.

If you either pass "exit" to the function, or else take out the parameter from the function declaration, it'll work — maybe. That "read" function is asynchronous, so I'm not sure how node will behave.

Sign up to request clarification or add additional context in comments.

Comments

1

Pointy’s right about the parameter shadowing the outer variable you’ve declared. However, what you’ll end up with is a horrible busy loop. Node.js is event-based; use its events properly.

function promptUser() {
    read({prompt: "> "}, function(err, result) {
        console.log();
        console.log(result);
        console.log("Type in more input or type 'exit' to close the program.");

        if(result !== "exit") {
            promptUser();
        }
    });
}

promptUser();

Comments

0

You aren't passing exit when you call the function. It should be:

    OutsideLoop( exit );

On the last line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.