I am doing :
eval(\'function(){ console.log(\"Hello World\"); }\')();
But that gives error :
Uncaught SyntaxError: Unexpected t
What you want is this:
eval( '(function(){ console.log("Hello World"); })()' );
Let's break it down. You have a self invoking function (a function that calls itself):
(function(){ console.log("Hello World"); })()
And you're passing it as a string argument to the eval
method:
eval( '(function(){ console.log("Hello World"); })()' );
Your main error is trying to call what eval
returns by adding parenthesis on the end of the eval
method call. If you want the function your passing to immediately invoke itself, the added parenthesis should be part of the thing your passing to eval
.
I'm assuming you're trying to do something other than call "Hello World", as you could simply do this:
eval( 'console.log("Hello World");' );
Or, dare I say:
console.log("Hello World");