0

While this code is fine:

var x = function() { };

This code is not:

function() { };

The top example creates an anonymous function and assigns it to x. The bottom example is a statement, where a function name is required, so it is a syntax error.

Now, it may seem pointless to define an anonymous function and not assign it anywhere, but here's an example that confronts the behavior:

var x = eval('function() { }');

Which should behave just like the first example, but is a syntax error.

Deep in the app I'm working on, we come to this issue. I want function() { } to be an expression.

A short explanation why is that this is a native OSX app calling javascript into a WebView. We have an evaluateJavascript function which the native layer can use to call arbitrary javascript. evaluateJavascript wraps the given code with try/catch for error-handling, because it's the only way to get detailed error information. So if you call myCallback = evaluateJavascript("function() { }"), we generate a function with the following body:

try {
    return eval('function() { }');
} catch(e) {
    // ....
}

And return the result.

5
  • But why do you need a function to evaluate in the first place? Just evaluate the statements you would have had in the function?
    – AmmarCSE
    Jul 24, 2015 at 17:35
  • The caller needs a function object returned.
    – tenfour
    Jul 24, 2015 at 17:36
  • Maybe this can help? IIFE
    – doldt
    Jul 24, 2015 at 17:37
  • @doldt hmm, good idea - just wrapping in parenthesis is OK to impose on the caller. Very elegant.
    – tenfour
    Jul 24, 2015 at 17:40
  • if you don't need closure (you probably don't/shouldn't), use Function() instead of eval()
    – dandavis
    Jul 24, 2015 at 18:12

4 Answers 4

2
  1. When possible, don't use eval. Another option to find errors is if you listen for errors on the window (or equivalent) object and import the scripts as <script>s which are added and removed immediately.
  2. Doing anything on the same line before function will cause function to be an expression

All of the following are valid (although useless)

0, function () {};
(function() {});
+function () {};
-function () {};
!function () {};
// etc

Function expressions like this are usually done for IIFEs, i.e.

(function (foo) {
    console.log(foo);
}('bar'));
// "bar" logged

But you can apply the style to your eval-ing. Either parenthesis or the comma operator should work for you

var code = 'function () {}';
var foo = eval('0, ' + code);
foo; // function () {}
1
  • I am using window.onerror, but this is not invoked for certain calls from native code. The incoming code doesn't necessarily need to be an expression; it can be any arbitrary JS. But with this, and the other answers, I think I have the solution. I think I will actually separate this into 2 different functions: evaluateJSExpression (with return val), and evaluateJSCode (no return val but it can be any block of js).
    – tenfour
    Jul 24, 2015 at 18:13
1

Can't you do

x = eval('y = function() {}')

?

1

You say var x = eval('function() { }'); should behave just like the first example. Why do you think so? Your eval argument

function() { }

is a statement and invalid as you point out above. You could make it an expression like this:

var x = eval('(function() { })');
1

Attempt/Approach- 1 : Below should work

var scope = {};
eval('scope.x = function() { return "Hello World"; }');
console.log(scope.x());

Output

Hello World
[Finished in 0.3s]

** Approach - 2 **

After reading link on IIFE insuggested in comments of above question, I tried below - and it seems to work as well.

var x = eval('(function() { return "Hello World"; })');
console.log(x());

However, I realized that with IIFE, we need to have code like (function(){})() - note that trailing (). However, in the Approach-2 code - I did not have the trailing (). Then, I looked up the eval documentation, and from it I came to know the following (which explains why Approach-2 works):

eval as a string defining function requires "(" and ")" as prefix and suffix

2
  • Hmm come to think of it, I guess expressions passed into my evaluateJavascript function cannot span multiple statements; they are expressions only. Thus I can get away with this. Or I think I prefer to wrap in parenthesis, as that should probably be done anyway.
    – tenfour
    Jul 24, 2015 at 17:44
  • Based on comments on your question about link to IIFE, parenethis approach seems elegant and right way
    – Wand Maker
    Jul 24, 2015 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.