Search code examples
javascriptreferenceerror

Catch a referenceError in js


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!


Solution

  • 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
        }
    }