lundi 22 février 2021

calculator: variable somehow undefined in "if else" statement

I'm trying to make a calculator with Javascript. I have a function that asks to input an operator. I want it to ask for an operator again if the user inputs anything else than *, /, + or -. Everything works fine if the right operator is given, however, after the wrong operator has been given as input, and the function is executed for a second time, the value of the operator is suddenly "undefined". And I am not sure why... When I call the function within the if statement, does it not jump back to the beginning of the function, where I declare the operator? Can anyone tell me what I've done wrong?

function getOperator() {
    var operator = getStringInputWithPrompt('Please enter the operator:');
    if ((operator !== "+") && (operator !== "*") && (operator !== "-") && (operator !== "/")) {
        console.log("\nSorry that was not a valid operator");
        getOperator();
    } else {
    return operator;  
    }
} 

Aucun commentaire:

Enregistrer un commentaire