Skip to content Skip to sidebar Skip to footer

Eval Always Returns Error When Executing A Function Having A Return Statement

This block of code always returns errors: eval('if(!var_a){return 0;}'); A statement like this works perfectly fine: eval('alert(1)'); A JavaScript statement such as eval('return

Solution 1:

This is because you are using return outside of the context of a function. Wrap your code in a function and return works fine. There are a few ways to do that. I suggest that you do not use any of them. Instead find a way to avoid eval. Regardless, here are some solutions:

eval('(function() { if(!var_a){return 0;} })()');

or

new Function('if(!var_a){return 0;}')()

Solution 2:

You can only return from within a function. Like so:

function foo() {
    if (x) alert("woo");
    else return 0;
    doMoreStuff();
 }

You're not in a function, so there's nothing to return from. Also, why are you using eval at all?

Solution 3:

In the first case, you are attempting to execute an expression with a return. In the second case, you are calling a function that returns a value. To do what you want, you can declare and invoke an anonymous function within the expression as follows...

eval('(function(){ if(!var_a){return 0;} })()');

Of course, if the question is just how to construct an evaluateable expression that includes a condition, you can use the "ternary" operator...

eval('var_a ? nil : 0');

Post a Comment for "Eval Always Returns Error When Executing A Function Having A Return Statement"