Home > OS >  How to create a simple calculator using switch case and function using Javascript
How to create a simple calculator using switch case and function using Javascript

Time:08-17

I'm new to Javascript and just finished learning switches and conditionals and I wanted to create my calculator where it first asks the user what they want to do and gets the two digits from them and goes ahead and alerts them with an answer. But every time I try to run the function it gives me an undefined error enter code here

let tell = prompt("What would you  like to do (*,/, ,-)");
let dig1 = prompt("Enter first Number");
let dig2 = prompt("Enter second Number")

function calculate(a,b) {
    let answer = tell;
    switch (a,b) {
        case "*":
            answer = a * b;
            break;
        case "/":
            answer = a / b;
            break;
        case " ":
            answer = a   b;
            break;
        case "-":
            answer = a - b;
            break
    }
}

alert(calculate(dig1,dig2))

CodePudding user response:

let tell = prompt("What would you  like to do (*,/, ,-)");
let dig1 = prompt("Enter first Number");
let dig2 = prompt("Enter second Number")

function calculate(a,b) {
    // check the value of the `tell` is one of these cases and return the result.
    switch (tell) {
        case "*":
            return a * b;
        case "/":
            return a / b;
        case " ":
            return a   b;
        case "-":
            return a - b;
        default:
            return "You didn't a correct opertor"
    }
}

alert(calculate( dig1,  dig2))

  • Related