Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function(){} and (function(){}) in javascript

Tags:

javascript

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>
like image 461
Kanagavelu Sugumar Avatar asked Apr 18 '14 12:04

Kanagavelu Sugumar


1 Answers

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(){};
like image 57
Karl-André Gagnon Avatar answered Oct 03 '22 04:10

Karl-André Gagnon