0

I know this type of question gets asked a lot, but I haven't seen any question with this type of declaration

(function(){
    myFuncName=function(myVar){
       // some logic
    };
}());

how does that differ from

function myFuncName(myVar){
// some logic
}
Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • This is basically [Anonymous function vs normal function](http://stackoverflow.com/questions/13323237/anonymous-function-vs-normal-function). The first creates an anonymous function and assigns it to `myFuncName`, in whatever lexical contact `myFuncName` refers to. The other is a function declaration which creates the name `MyFuncName` in the current variable context. – Raymond Chen Mar 15 '13 at 22:17

3 Answers3

1

What your doing is creating an anonymous function that also has a closure in it. Read more about closures here.

Basically a closure means that you have declared a function inside of another function. Which will let you access local variables after the first function exits.

Normally you would not be able to do this since they would be out of scope.

As for the other part. You can find a very useful guide to what's happening here Why do you need to invoke an anonymous function on the same line?.

To sum it up though, you have created an anonymous self-invoking function expression.
The self-invoking comes from the fact that () immediately follows the function expression.

Community
  • 1
  • 1
Ryan
  • 5,644
  • 3
  • 38
  • 66
1

The first one is an anonymous function and there is no way you can reference to and call it later on, so you just executes instantly ( ) once it had been created!

(function(){
    alert(1)
}())

The second one is a reference function that you can call it anytime later. It wont gets executed unless you call it explicitly

spaceman12
  • 1,039
  • 11
  • 18
  • This is a slight misread of the question, because the first one assigns the anonymous function to `myFuncName`, which is the way it can be referenced later on. The subtle difference is the context in which `myFuncName` is visible. – Raymond Chen Mar 15 '13 at 22:19
0

Here's a link which explains the the function declarations in javascript.

Sanket Parikh
  • 469
  • 3
  • 5