Why this kind of function invocation is wrong in JavaScript?
Asked Answered
O

1

6

I'd like to create an anonymous function and then invoke it immediately.

1) This will bring a syntax error. Why?

function ()
{
    alert("hello");
}();

2) wrap the function definition with () and it works.

(function ()
{
    alert("hello");
})();

3) or, assign the anonymous function to a variable. It works.

var dummy = function()
{
    alert("hello");
}();

Why the first way doesn't work?

Ostosis answered 22/3, 2009 at 6:50 Comment(2)
So apparently it's not a syntax error?Tocopherol
As sth said, it is a syntax errorLeshia
D
13

The ECMAScript Language Specification, section 12.4, says:

An ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

So your case 1 is not allowed, because it might lead to ambiguities in the language. The other cases are different kinds of statements (not ExpressionStatements) in which this is not a problem, so the construct is allowed there.

Depersonalize answered 22/3, 2009 at 7:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.