Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61401

How safely eval() javascript to get indication if it can be evaluated and prevent exceptions?

Consider the following code. JsFiddle

var a = { prop : 1};
var b = { prop : 2};
var c = { prop : 3};
var d = { prop : 4};
var e = { prop : 5};

var obj = { a : a, b : b, c : c, d : d, e : e, f : 'f stands for fail' };

$(function(){
    console.log('try/catch');
    try{
        for(var p in obj){
            if (typeof p != 'undefined')
                console.log(eval(p));
        }
    }catch(e){}
});

$(function(){
    console.log('check typeof and you will get string');
    for(var p in obj){
        if (typeof p != 'undefined')
            console.log(eval(p));
    }
});

Is there a way to check in 'oneliner' (like typeof p != 'undefined') without having to use try catch that one would get indication that contents of eval() are unevaluatible for whatever reason. Basically to get true somehow if it evals without errors and false if it fails.

Upvotes: 1

Views: 56

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382122

You can check a code is syntactically valid without evaluating it using the Function constructor.

function isSyntacticallyValid(p){
    try {
        new Function(p);
        return true;
    } catch(e){} // e will typically be a SyntaxError
    return false;
}

It's simply impossible in the general case to check in advance the code would really evaluate without error and in finished time (it's an undecidable problem).

Example :

var codes = [
  "y = x+2", // is OK
  "alert('Hey!')", // this one too
  "random garbage" // but not this one
];

codes.forEach(function(p){
  try {
    new Function(p);
  } catch(e){
    console.log("Bad code : ", p);
  }
});

Upvotes: 4

Related Questions