Reputation: 31
Recently I saw a function in someone else's code which looked like below:
function xyz(){ //function code here ;
} ();
I dont understand the ();
after the function definition.
Can someone tell me what is the significance of ();
and when should one use it in JavaScript ?
Upvotes: 3
Views: 260
Reputation: 382092
The code you show doesn't compile.
With parenthesis added, this would be a named immediately invoked function :
(function xyz(){ //function code here ;
}) ();
Most often those functions are anonymous :
(function(){
var a; // a isn't visible outside
// code using a
})();
The code is directly called, as without a function definition, but the point of such a function is to define a scope (which can only be the global scope or a function) so that the scope's variable don't leak in the enclosing one. This pattern is very useful for making your code clean : You don't add any variable in the outer scope and you can't erase an existing one.
Here the function also has a name, which can be used inside for recursion.
(function xyz(){
var a; // a isn't visible outside
// code using a and calling xyz
})();
Upvotes: 3