Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these two types of self executing function on JavaScript

Tags:

javascript

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?

like image 796
tugberk Avatar asked Dec 21 '22 05:12

tugberk


1 Answers

The code below demonstrates what's happening. In reality, the foo and bar variables don't exist, and the functions are anonymous.

var foo = function() {}
foo();

var bar = function(d){}
bar(document.documentElement);

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:

for(var i=0; i<10; i++) {
    document.links[i].onclick = function(){
        alert(i); //Will always alert 9
    }
}

After implementing the closure:

for(var i=0; i<10; i++) {
    (function(i){
        document.links[i].onclick = function(){
            alert(i); //Will alert 0, 1, ... 9
        }
    })(i);
}
like image 183
Rob W Avatar answered Dec 24 '22 01:12

Rob W