Why is an anonymous function in itself a syntax error in javascript?

If I try to execute a script whose only source line is an object:

{prop:'value'} 

it is well versed (in both V8 and UglifyJS). Similarly, I can put the string or number myself as source code, and no syntax error is reported.

However, both V8 and UglifyJS themselves complain:

 function(){} 

I get Uncaught SyntaxError: Unexpected token ( .

Why is this interrupted when the object in the first example is beautiful? Only objects in javascript not working?

I understand that declaring an anonymous function without doing it will do nothing; it's not a question. I want to know why this is causing a parsing error.

+8
javascript syntax anonymous-function parsing grammar
source share
2 answers

From the ECMAScript specification, section 12.4, in expressions:

Please note that ExpressionStatement cannot start with an opening curly brace, because this can make it ambiguous with a block. Also, an ExpressionStatement expression cannot begin with the function keyword, because this can make it ambiguous with FunctionDeclaration.

Although functions are just objects, remember that you can declare functions yourself without using your objects in expressions. This is where the ambiguity is. Of course, you can never declare an anonymous function yourself (since you cannot reference it in any case), but since I cannot find anything in the specification that distinguishes anonymous function from the named functions, I suspect that this applies to both.

To eliminate the ambiguity, you need to enclose it in parentheses, so it will always be considered as an expression:

 (function(){}) 
+11
source share

{prop:'value'} not parsed as an object, it is simply parsed as a block that has the label prop .

You need () to enclose it in parsing as an expression.

({prop: 'value'}) will be parsed as an expression of the object.

(function(){}) will be parsed as an expression of a function.

+5
source share

All Articles