Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why function statement requires a name?

Tags:

javascript

Why I can write

 var foo = function(){}(); 

But can not

 function(){}(); 

Are there are any design reasons?

like image 903
Stan Kurilin Avatar asked Nov 10 '11 21:11

Stan Kurilin


People also ask

Does a function need a name?

Functions stored in variables do not need function names. They are always invoked (called) using the variable name.

How do you define a function called as name?

Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

What is JavaScript function statement?

The function statement declares a function. A declared function is "saved for later use", and will be executed later, when it is invoked (called). In JavaScript, functions are objects, and they have both properties and methods. A function can also be defined using an expression (See Function Definitions).

What is anonymous function in JS?

In JavaScript, an anonymous function is that type of function that has no name or we can say which is without any name. When we create an anonymous function, it is declared without any identifier. It is the difference between a normal function and an anonymous function.


1 Answers

The first example is an assignment: the right-hand side is an expression, and the immediate execution of an anonymous function makes sense.

The second example is a declaration: once the closing "}" is hit the declaration has ended. Parens on their own don't make sense--they must contain an expression. The trailing ")" is an error.

Standalone declarations must be turned into expressions:

(function() {})();  // Or... (function() {}()); 

The first makes the declaration an expression, then executes the result. The second turns both declaration and execution into an expression.

See also When do I use parenthesis and when do I not?

like image 141
Dave Newton Avatar answered Sep 20 '22 23:09

Dave Newton