eval javascript, check for syntax error eval javascript, check for syntax error javascript javascript

eval javascript, check for syntax error


You can test to see if an error is indeed a SyntaxError.

try {    eval(code); } catch (e) {    if (e instanceof SyntaxError) {        alert(e.message);    }}


When using try-catch for catching a particular type of error one should ensure that other types of exceptions are not suppressed. Otherwise if the evaluated code throws a different kind of exception it could disappear and cause unexpected behaviour of the code.

I would suggest writing code like this:

try {    eval(code); } catch (e) {    if (e instanceof SyntaxError) {        alert(e.message);    } else {        throw e;    }}

Please note the "else" section.


According to the Mozilla documentation for eval:

eval returns the value of the last expression evaluated.

So I think you may be out of luck. This same document also recommends against using eval:

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways of which the similar Function is not susceptible.

So regardless, please be aware of the risks before using this function.