Search code examples
javascript

error Uncaught SyntaxError: Unexpected string


var calc = {
  '+': function (x, y) { return x + y },
  '-': function (x, y) { return x - y },
  '*': function (x, y) { return x * y },
  '/': function (x, y) { return x / y }
};
var firstNum = prompt("first number");
var secondNum = prompt("second number");
var opr = prompt("+, -, * or /?");
var ans = calc['+'](1,2);
console.log("the answer is " + ans "!");

this is my code, it gives me an error, why?

can someone help me?


Solution

  • Firstly you forgot a + in

    "the answer is " + ans "!";
    

    and you need console.log(ans) or alert(ans); in order to see the result:

    var calc = {
        '+': function (x, y) { return x + y },
        '-': function (x, y) { return x - y },
        '*': function (x, y) { return x * y },
        '/': function (x, y) { return x / y }
    };
    var firstNum = prompt("first number");
    var secondNum = prompt("second number");
    var opr = prompt("+, -, * or /?");
    var ans = calc[opr](firstNum,secondNum);
    console.log("the answer is " + ans +"!");
    alert("the answer is " + ans +"!");