0

I am building a small project of making a simple Calculator using HTML, CSS & Javascript. I am using eval function. I wanted to have both features of Math Error and Syntax Error like a real calculator and I have successfully added Math Error feature but I couldn't add the Syntax Error. So the problem is, If I do this:

var a = "2+2";
alert(eval(a));

It shows the right answer: 4. But If I do this:

var a = "2++2";
alert(eval(a));
Or this:

document.write(eval(a));

then the eval function is not executed and shows nothing on screen. It shows this on the console.

Uncaught SyntaxError: Invalid left-hand side expression in postfix operation

But I want it to show just a "Syntax Error" on the screen.

5
  • 2
    When I run that, I do get a Uncaught SyntaxError: Invalid left-hand side expression in postfix operation. Commented Dec 27, 2020 at 15:55
  • Does this answer your question? eval javascript, check for syntax error Commented Dec 27, 2020 at 16:01
  • It works for me (SyntaxError: invalid increment/decrement operand) Commented Dec 27, 2020 at 16:01
  • @Bergi I need to edit my question. Commented Dec 27, 2020 at 16:05
  • 1
    Just use try/catch to handle the error by displaying it Commented Dec 27, 2020 at 16:17

1 Answer 1

3

Use a try/catch block to catch the exception thrown by eval, and use .name on the error object to print only its class name. Which, in this case, is SyntaxError.

var a = "2++2";
try {
    alert(eval(a));
} catch (e) {
    console.error(e.name);
}
You can also do custom handling for different errors (as well as custom error messages) by simply inspecting e.name and printing whatever you want.

Note that the console.error prints to stderr, instead of the usual stdout from console.log. You can change this if you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.