Catch a referenceError in js

jacobdo picture jacobdo · Sep 12, 2015 · Viewed 10.5k times · Source

I have a textarea where user can enter javascript code which upon press of the button would be passed to eval().

I am having trouble catching the referenceError for cases when a user enters something like this:

var myName = Maria;

instead of

var myName = "Maria";

Thank you for you time!

Answer

Suresh Atta picture Suresh Atta · Sep 12, 2015

Ok, as you said you understood the pit's of eval(), here i'm proposing a solution.

try {
    var myName = Maria;
} catch (e) {
    if (e instanceof ReferenceError) {
        // Handle error as necessary
    }
}