"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>