0

Possible Duplicate:
JavaScript scope and closure
JavaScript - self executing functions

What is the difference between the following code:


var someVar = (function(){
   // some code
})();

And


var someVar = function(){
   // some code
};

Can you point me to tutorials on the usage and explanation of first code?

It is hard to find the answer on Google, so I thought I would ask it here.

Thank you.

Community
  • 1
  • 1
Ibrahim
  • 1,247
  • 3
  • 13
  • 21

1 Answers1

1

First case

Will be created and executed anonymous function. Function result will be stored in someVar.

var someVar = (function(){
    console.log('function executed');
    return 1;
})();
// function executed
console.log(someVar);
// 1

Second case

Will be created anonymous function and it's reference will be stored in someVar.

var someVar = function(){
    console.log('function executed');
    return 1;
};

var result = someVar();
// function executed
console.log(result);
// 1
KAdot
  • 1,997
  • 13
  • 21