How can I make it so that at any point during my function the user can type "reset" and it will take them back to the beginning of my function?

38 views Asked by At
let level = 0;
let usersName;
let path;

const getBotReply = (msg) => {

    if (level === 0) {
        level = 1;
        usersName = msg;
        return "Chur " + usersName + ". Do you live in Raglan?";
    }

    if (level === 1) {
        level = 2;
        if (msg === "yes") {
        path = "left-yes";
        return "Do you know how to surf?";
    }

        if (msg === "no") {
        path = "right-no";
        return "Are you from Auckland?";
    }
}

Basically I want it so that instead of typing yes or no. The user will type reset and it will return to "level 0"

I've tried:

    if (msg === "reset") {
    level = 0;
}
2

There are 2 answers

1
Joshua Mendoza On

in this case, I believe it would be preferable to include a while loop.

while(msg === "reset"){level = 0};
2
Wobbley On

If you put your if-check for reset at the top then you have done it correctly, and you simply forgot a return in the solution you suggested?

If you don't include a return stament in the if-check the function will just continue, so it will run the next if check, which matches the level being 0 and it will assume that "reset" is the name of the user.

So if you include

if(msg === "reset"{
 level = 0
 return
}

It should work just fine, you can leave the return blank or include a message. I included a JS fiddle which is literally your code with the fixed if check: https://jsfiddle.net/5tu7c20n/