views:

99

answers:

3

In JavaScript is there a way to get the "value" of a statement in the same way that function() { return eval("if (true) { 1 }"); } returns "1";

function() { return if (true) { 1 } } and all similar permutations I've tried are not valid syntax.

Is eval just blessed with special powers to determine the "last" value of a statement in an expression?

Use case is a REPL that evaluates arbitrary expressions and returns the result. eval works, but I want to wrap it in function.

+1  A: 
function(expr) { return eval(expr); }

But that really doesn't do anything more than what eval does, so I'm guessing you must want to do things with the return value of eval before returning it?

E.g.:

function custom_eval(expr) 
{
  var result = eval(expr);
  if ((typeof result))=="string")
  { 
     alert("The expression returned a string value of: " + result); 
  }
  if ((typeof result))=="number")
  {
     alert("The expression returned a number with value: " + result);
  }
  //and so on and so forth...
  return result;
 }

 var bob = custom_eval("x=\"bob\";x");
 alert(bob);

(More on the typeof operator)

Mike Atlas
I don't think this what he was looking for, but it's worth mentioning that `typeof` is NOT a function, and should be used as `typeof result` rather than `typeof(result)`.
bcherry
This still uses `eval` which executes *any* code within string `expr`. This can be very dangerous, as the OP describes that the string can contain "arbitrary expressions".
Marcel Korpel
@Marcel : The OP did not merely say that the string can contain any arbitrary expression, the OP said that he wants to EXECUTE those arbitrary expressions (evaluate was his word).
slebetman
@Marcel: To determine the value of the final expression, it must be evaluated (executed), otherwise the OP will sadly have to solve the halting problem http://en.wikipedia.org/wiki/Halting_problem.
Mike Atlas
@slebetman: You're right.
Marcel Korpel
@Mike: Interesting, thanks for the link. And I have to admit that I also cannot solve this without the use of `eval`.
Marcel Korpel
I'm not looking to solve the halting problem :)
tlrobinson
A: 

You can use || to get the first value that isn't null/undefined/0:

var t = 1 || 'b' || 3 || 'd'; // assigns 1

var t = 0 || null || undefined || 'd'; // assigns d

You can use && to get the last value, if no short-circuiting null/undefined/0 is found first:

var t = 1 && 'b' && 3 && 'd'; // assigns d

var t = 0 && null && undefined && 'd'; // assigns 0
machine elf
A: 

To evaluate arbitrary javascript code in javascript you have three options

  • eval. This is usually considered as "dangerous", but since javascript is executed on the client's computer, they can only harm themselves (unless you provide clients with a way to share their codes).
  • Function constructor. The same concerns apply.
  • write a javascript interpreter. This is definitely tricky for "arbitrary" code.
stereofrog