I always use the following self executing function in order to avoid exposing my code to global scope in JavaScript:
(function() {
//Code comes here
})();
I believe that this is also called self executing anonymous function as well. Sometimes, I also see the below code used for the same purpose:
(function(d){
//Code comes here
})(document.documentElement);
I am not sure what makes the difference here so I am asking this question.
What is the difference (or are the differences) between these two types of self executing function on JavaScript?
The code below demonstrates what’s happening. In reality, the
fooandbarvariables don’t exist, and the functions are anonymous.The
(function(d){})(d)method is called a closure. It’s used to pass variable values which are subject to change, such as in loops.Have a look at a practical an example:
After implementing the closure: