Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 0') always gives an error when its intention is to make the script stop further execution.

eval simply gives unwanted errors when it is run in some block of code and a return statement is in it.

like image 844
user1124581 Avatar asked Jul 01 '26 09:07

user1124581


1 Answers

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;}')()

like image 51
Hemlock Avatar answered Jul 02 '26 22:07

Hemlock