I am doing :
eval(\'function(){ console.log(\"Hello World\"); }\')();
But that gives error :
Uncaught SyntaxError: Unexpected t
The eval
operator expects a Program as input, and the grammar of JavaScript requires that all
top-level program elements are either declarations or statements.
The spec says:
Let prog be the ECMAScript code that is the result of parsing x as a Program.
function
can't start a top-level statement, but it can start a function declaration, but only when it has a name.
That's why you get "Unexpected token ("; it expects a function name before the parenthesis that opens the argument list.
As others have noted, to eval
a function, you need to trick the JavaScript parser into finding an expression where it expects a statement. Wrapping the body in parentheses is one way to do this.