Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use js eval to return a value?

Tags:

javascript

I need to evaluate a custom function passed from the server as a string. It's all part of a complicated json I get, but anyway, I seem to be needing something along the lines:

var customJSfromServer = "return 2+2+2;"
var evalValue = eval(customJSfromServer);
alert(evalValue) ;// should be "6";

Obviously this is not working as I expected. Any way I can achieve this ?

like image 343
Radu094 Avatar asked Sep 13 '11 08:09

Radu094


People also ask

Does eval return a value?

If code contains an expression, eval evaluates the expression and returns its value. If code contains a JavaScript statement or statements, eval( ) executes those statements and returns the value, if any, returned by the last statement. If code does not return any value, eval( ) returns undefined .

What does eval return in JS?

eval() returns the completion value of statementsFor if , it would be the last expression or statement evaluated. The following example uses eval() to evaluate the string str .

How do you use eval instead of function?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().

Can eval be used as a variable?

In other words, it's seen as a variable defined in the body of eval() . You can use x in expression , and eval() will have access to it. In contrast, if you try to use y , then you'll get a NameError because y isn't defined in either the globals namespace or the locals namespace.


2 Answers

The first method is to delete return keywords and the semicolon:

var expression = '2+2+2';
var result = eval('(' + expression + ')')
alert(result);

note the '(' and ')' is a must.

or you can make it a function:

var expression = 'return 2+2+2;'
var result = eval('(function() {' + expression + '}())');
alert(result);

even simpler, do not use eval:

var expression = 'return 2+2+2;';
var result = new Function(expression)();
alert(result);
like image 181
otakustay Avatar answered Oct 16 '22 09:10

otakustay


If you can guarantee the return statement will always exist, you might find the following more appropriate:

var customJSfromServer = "return 2+2+2;"
var asFunc = new Function(customJSfromServer);
alert(asFunc()) ;// should be "6";

Of course, you could also do:

var customJSfromServer = "return 2+2+2;"
var evalValue = (new Function(customJSfromServer)());
alert(evalValue) ;// should be "6";
like image 10
Matt Avatar answered Oct 16 '22 09:10

Matt