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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With