Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome - eval - function()

Why is Chrome throwing

SyntaxError: Unexpected token (

when i try to call:

eval("function(){alert('test')}")

?

like image 764
Mike Pandorium Avatar asked May 12 '11 14:05

Mike Pandorium


2 Answers

Chrome is throwing the SyntaxError because you either need () around your function or you need to name it.

//This defines a as the function
eval("function a(){alert('foo')}");

//This returns the anonymous function
eval("(function(){alert('foo')})");

either should work properly.

like image 195
zellio Avatar answered Sep 22 '22 22:09

zellio


Oddly, Safari 5.1 and Chrome 13.0.782.220 do require outer parens in this special case of anonymous functions. I have no idea why, as the expression is no more ambiguous or less useful without the parens than with. Firefox 6.0.2 is perfectly happy without the parens.

Does anyone know whether the Javascript language spec specifies these outer parens and whether they're necessary for cases other than anonymous functions?

like image 38
Conal Avatar answered Sep 23 '22 22:09

Conal