Reputation: 2185
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.
Under which all scenarios we should prefer to use above syntax?
What are the advantages/benefits do we get by using above syntax?
Upvotes: 2
Views: 82
Reputation: 67207
"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>
Upvotes: 2