Rosa
Rosa

Reputation: 33

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 enters anything else than *, /, + or -. Everything works fine if the user enters one of the accepted operators, however, if the wrong operator has been entered, and the function is executed for a second time, the value of the operator is somehow "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 getOperator(), where I assign a value to the operator variable? 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;  
    }
} 

Upvotes: 3

Views: 98

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386680

You need to return the result of the recursive calling.

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

console.log(getOperator());

Because of writing a calculator, you could use an object for the operators and check if the operator exist and take the function for this operator.

const
    operators = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    };

function getOperator() {
    let operator = prompt('Please enter the operator:');
    if (operator in operators) return operator;
    return getOperator();                                // omit else after return
}

console.log(getOperator());

Upvotes: 2

Bill the Lizard
Bill the Lizard

Reputation: 405955

Inside the if, you make a recursive call to getOperator() but you don't do anything with its returned value. You can return it immediately.

console.log("\nSorry that was not a valid operator");
return getOperator();

Upvotes: 2

Related Questions