Search code examples
javascriptscopees5-shim

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?


Solution

  • 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.