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.
From the ECMAScript spec, section 12.4 on expression statements:
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: