Search code examples
javascriptif-statementprompt

How can I use Prompt, if and else in Javascript function to select arithmetic symbol and do some calculation with the user inputs


I am a novice in this and it is really making me to lose my hair; I can find what I'm doing wrong, please help. I am doing this in javascript. It doesn't show any error, nor display any result either. This is what I have:

    var sumIt;
    var subtractIt;
    var multiplyIt;
    var divideIt;
    var operatorOpt = prompt("Select operator");
    
    function showResult(whatResult) {
        document.write(whatResult);
        document.write("<br>");
    }
    
    var doSomething = function(num1, num2) {
        if (operatorOpt == sumIt) {
            showResult("The result is: " + (num1 + num2));
    
    
        } else if (operatorOpt == subtractIt) {
            showResult("The result is: " + (num1 - num2));
    
        }  else if (operatorOpt == multiplyIt) {
            showResult("The result is: " + (num1 * num2));
    
    
    }  else if (operatorOpt == divideIt) {
            showResult("The result is: " + (num1 / num2));
    
    doSomething(parseInt (prompt("Enter first number: ")) ,  parseInt (prompt("Enter second number: ")))


Solution

  • It seems that your are missing a closed bracket in the definition of doSomething function. The following code seems to work produce the desired results

    var sumIt = "+";
    var subtractIt = "-";
    var multiplyIt = "*";
    var divideIt = "/";
    var operatorOpt = prompt("Select operator");
    
    function showResult(whatResult) {
        console.log(whatResult);
        document.write(whatResult);
        document.write("<br>");
    }
    
    var doSomething = function(num1, num2) {
        if (operatorOpt == sumIt) {
            showResult("The result is: " + (num1 + num2));
        } else if (operatorOpt == subtractIt) {
            showResult("The result is: " + (num1 - num2));
        }  else if (operatorOpt == multiplyIt) {
            showResult("The result is: " + (num1 * num2));
        }  else if (operatorOpt == divideIt) {
            showResult("The result is: " + (num1 / num2));
        } else {
          console.log("No Condition reached");
        }
    
     }
    
     doSomething(parseInt (prompt("Enter first number: ")) ,  parseInt (prompt("Enter second number: ")));