Team,
I received syntax error when using function(){}
, but not when (function(){})
, why?
I know (function(){})
is still declaration '(function(){})()
' is the expression.
But why this declaration is not possible with simply function(){}
without covering with (... )
?
<html>
<body>
<script>
function(){} //**Syntax error**
(function(){}) //Declaration
(function(){})() //Expression; so executed.
</script>
</body>
</html>
You can't have an anonymous function that is assigned to nothing. There is no use since because it is not assigned, you can't call it by a variable name and since it as no name, you can call it by its name.
(function(){})
will work because the parenthesis are evaluating the function and returning a function reference. You can then call that function with .call()
, .apply()
or ()
.
The last one is completly different, it call directly the function. It is the same as the second method, but with a direct call.
List of good function declaration (ok there is also expressions, shhh):
function name(){};
(function(){}); //Can't call that function latter since it has no reference.
var name = function(){};
var name = (function(){});
var name = function otherName(){};
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