3

I've seen some people define functions like I do:

function stuff(){ /*code here*/ }

And I've seen others do this:

(function stuff(){ /*code here*/ })();

What's the difference in having the parenthesis outline the function? Does it actually do anything?

Note: This may be a duplicate, but I didn't find the answer online since I didn't phrase it very well.

Jerry
  • 492
  • 3
  • 11
  • 1
    Are you sure your didn't mean (function stuff () { /*code here*/ })(); – Mr Rubix Mar 15 '16 at 22:20
  • 1
    This was the beginning of my answer: The first one is a function **declaration**. Function declarations create a new binding in the current scope, so you can reference the function by its name. The second one is a function **expression**. Inside the "grouping operator" (`(...)`) can only be expressions, hence the function definition is interpreted as function expression. The name of the function doesn't create a binding outside the function itself. The function can only be accessed by its name inside itself. – Felix Kling Mar 15 '16 at 22:23
  • Thanks for the help everyone. – Jerry Mar 15 '16 at 22:28

2 Answers2

4

What you're thinking of is an immediately-invoked function expression and can be used to produce lexical scoping (i.e. private variables,etc.). Check out the wiki article here.

Here's an example from the wiki:

var counter = (function(){
 var i = 0;

 return {
   get: function(){
     return i;
   },
   set: function( val ){
     i = val;
   },
   increment: function() {
     return ++i;
   }
 };
})();

In this case, i is not available on the outside.

Luka Jacobowitz
  • 19,651
  • 5
  • 34
  • 54
2

You've probably seen others do this:

(function stuff(){ /*code here*/ })();

That line will define a function and immediately execute it.

pishpish
  • 2,359
  • 11
  • 21