Reputation: 1333
I would like to ask that what the main difference between
(function(){
....
....
})();
and
function() {
....
....
}();
Upvotes: 1
Views: 63
Reputation: 156
They aren't really function signatures, they are Immediately-invoked function expressions (IIFE), and usually these are the two forms:
(function(){
/* ... */
})();
and
(function(){
/* ... */
}());
the parenthesis cause the function to be treated as a function expression. without them, the function will be treated as a function declaration
Upvotes: 0
Reputation: 1441
The first one is immediately invoked function, the second one is invalid JS, because when the parser encounters the function
keyword, it find it as a function declaration, but not as a function expression.
For immediately invoked function best way is
(function(){ ... }());
or
(function(){ ... })();
But you can also prefixing the function with a unary operator, it will be save a byte
!function(){ ... }();
~function(){ ... }();
-function(){ ... }();
+function(){ ... }();
Upvotes: 0
Reputation: 18566
The first one is a Self Invoking Function.
(function(){
....
....
})();
The function will be invoked by itself. It's mostly used for wrapping the code inside to prevent the variables from polluting the global namespace.You can notice it in popular libraries such as jQuery.
Another use case of it is:
As javascript is function scoped language when compared to other languages which are usually block scoped. If you want to create local variables inside function you can use IIFE for that purpose as well.
The second one is actually a syntax error. But it can be like
(function(){
....
....
}());
It's another way of representing the self invoking function.
Upvotes: 1