2

For below piece of code, I am aware that its an automatic function execution code (I saw it being used inJQuery).

var f = function() {

  // function body code
  // ...
  // ...

}();

What I want to understand is its usage.

  1. Under which all scenarios we should prefer to use above syntax?

  2. What are the advantages/benefits do we get by using above syntax?

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
ScrapCode
  • 2,109
  • 5
  • 24
  • 44
  • 2
    Possible duplicate of [What is the (function() { } )() construct in JavaScript?](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – Rick Runyon Mar 04 '16 at 07:39
  • @RickRunyon, My question is different than the one you mentioned. I wanted to understand its usage scenarios. – ScrapCode Mar 04 '16 at 08:50

1 Answers1

2

"Immediately invokable function expression" is the right name for it. And its usages are many, basically it will tightly wrap the scope and will not permit access to its variable to outside scope unless we are intentionally doing it.

And you can build singleton pattern by using it. One of the usages of Singleton pattern is to amend data encapsulation. Like setters and getters.

Possible usage situation:

<script src="someLibrary.js"></script> //And it uses a global variable called x
<script>
  var x = 10; //Now at this situation, 
              //the x belongs to someLibrary will be overridden here.
</script>

So in order to avoid such conflicts, we can use IIFE,

<script>
  (function(){
    var x = 10; 
    .
    .
    //Other codes goes here.
  })();
</script>
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • 1
    *"Singleton pattern is nothing but implementing data encapsulation"* - Um...there's a little more to it than that. And indeed a singleton object could have methods but no data of its own. – nnnnnn Mar 04 '16 at 07:55
  • @nnnnnn yeah `nothing but` should have been removed. I was just trying to say an usage of IIEF by quoting singleton pattern. :) – Rajaprabhu Aravindasamy Mar 04 '16 at 07:58
  • _"it will tightly wrap the scope and will not permit access to its variable to outside scope"_ - The normal functional will also not allow access to its variables outside its scope. I didn't understand you. – ScrapCode Mar 04 '16 at 09:12
  • 1
    @A.R. Yes. `var func = function(){ var x; }` is equal to `(function(){ })();`. Except one thing, that is normal function can be called multiple times in other places also. But IIEF cannot. – Rajaprabhu Aravindasamy Mar 04 '16 at 09:19