Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you pass a global variable to a function?

I've seen the same code written both ways and wonder if there's any tradeoff between them.

Method 1:

(function(i) {
    // Do something to i now
}(global_variable))

Method 2:

(function() {
    // Do something to global_variable now
}())

Why would you pass a global variable to a function if it's going to exist in that scope anyway?

like image 324
CamJohnson26 Avatar asked Mar 12 '26 23:03

CamJohnson26


2 Answers

In this case, it gives clear instructions that this function uses a global and creates an easier to type alias. Also, it makes accessing the variable a little faster because it doesn't need to search all the scopes until it finds it in the global scope.

In the case of regular functions, not an iife as in your example, it makes your function more testable because you can mock the global that is passed in more easily.

like image 74
Juan Mendes Avatar answered Mar 15 '26 12:03

Juan Mendes


for aliasing purposes for example:

(function(leeloo){

    //inside here you can use the short term

})(LeeloominaiLekataribaLaminaTchaiEkbatDeSebat)

//this would be similar, it's a matter of preference
(function(){
    var leeloo = LeeloominaiLekataribaLaminaTchaiEkbatDeSebat;

    //...
})()

or to enclose a value, like this example:

(function($){

    //in here, $ preserves the passed/injected value, 
    //even if the global value changes

})(jQuery.noConflict())

this way you could even use multiple versions of jQuery in the same page.

like image 22
Thomas Avatar answered Mar 15 '26 11:03

Thomas