Why I can write
var foo = function(){}();
But can not
function(){}();
Are there are any design reasons?
Functions stored in variables do not need function names. They are always invoked (called) using the variable 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.
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).
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With