I have the following string expression:
string_expression = "var sum = 0;\nfor (var i = 0; i < 100; i++) {\n var index = i + 1;\n sum += (index / ((index * Math.sqrt(index + 1)) + ((index + 1) * Math.sqrt(index))))\n}\nalert(sum)
If I use eval() it works fine:
eval(string_expression)
But if I use Function, like this:
Function("return " + string_expression)();
....I get the following error:
Uncaught SyntaxError: Unexpected token 'var'
Why would this behave differently? I am looking for an alternative to eval()
for security reasons, and thought the Function
approach would work the same with string expressions. Is there a better alternative to eval()
that works the same in terms of being able to parse string expressions?
Because you're feeding different things into them. return var sum = 0
is a syntax error. For similar behavior, leave out the return
. Your string expression alert
s rather than returning a value:
var string_expression = "var sum = 0;\nfor (var i = 0; i < 100; i++) {\n var index = i + 1;\n sum += (index / ((index * Math.sqrt(index + 1)) + ((index + 1) * Math.sqrt(index))))\n}\nalert(sum)";
Function(string_expression)()
If you want it to return the value, you'll have to modify the string; here I've changed alert(sum)
to return sum
:
var string_expression = "var sum = 0;\nfor (var i = 0; i < 100; i++) {\n var index = i + 1;\n sum += (index / ((index * Math.sqrt(index + 1)) + ((index + 1) * Math.sqrt(index))))\n}\nreturn sum;";
const sum = Function(string_expression)();
alert(sum);