Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an anonymous function on its own a syntax error in javascript?

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

{prop:'value'}

it parses fine (in both V8 and UglifyJS). Similarly I can put a string or number on its own as source code and there is no syntax error reported.

However, both V8 and UglifyJS complain about this on its own:

function(){}

I get Uncaught SyntaxError: Unexpected token (.

Why does this break when the object in the first example is fine? Aren't functions just objects in javascript?

I realise declaring an anonymous function without executing it won't do anything; that's not the question. I want to know why it causes a parse error.

like image 802
Flash Avatar asked Sep 08 '12 09:09

Flash


2 Answers

From the ECMAScript spec, section 12.4 on expression statements:

Note that an ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

Although functions are just objects, remember that you can declare functions on their own without really making use of their objects in expressions. That's where the ambiguity lies. Granted, you can never declare an anonymous function on its own (as you won't be able to reference it anyway), but as I can't find anything in the spec that distinguishes between anonymous function and named function declarations, I suspect this applies to both.

In order to resolve the ambiguity you need to wrap it in parentheses, so it will always be treated as an expression:

(function(){})
like image 133
BoltClock Avatar answered Oct 04 '22 02:10

BoltClock


{prop:'value'} is not parsed as an object, just parsed as a block, which has a label prop.

You need () to enclose it to parsed as an expression.

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

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

like image 20
xdazz Avatar answered Oct 04 '22 02:10

xdazz