Search code examples
javascriptiife

What is the purpose of declaring a parameter named “undefined” in IIFEs?


I have noticed jQuery and related keynote plugins like jQuery.UI pass undefined as a parameter into anonymous functions used in their module definitions, like so:

(function($, undefined) { ... })(jQuery);

Alternatively, I have noticed other plugins recommended by jQuery and/or others do NOT pass undefined in as a parameter.

This is probably a silly question, but...

Shouldn't it always be available anyway? Why pass it in? Is there some sort of other purpose or trick going on here?


Solution

  • There are two reasons for that:

    1) If undefined is a variable in the function scope rather than a global object property, minifiers can reduce it to a single letter thus achieving a better compression rate.

    2) Before ES5*, undefined was a property of the global object without write-protection. So it could be overwritten, resulting in strange and unexpected behavior. You could do something like this:

    var test = 123;
    undefined = 123;
    if (test === undefined){
       // this will actually be true, since undefined now equals 123
    }
    

    By having an function argument undefined (the name actually does not matter) which you don't pass a parameter to, you could make sure you have a variable which really is undefined so you can test "undefinedness" against this variable.

    Btw. the safest method to test for undefined is: typeof ( var ) === 'undefined'

    (*) With EcmaScript 5, the global properties undefined, NaN and Infinity became readonly. So with its general adoption in all modern browsers - of course with the exception of IE 9 - overwriting those values was not possible anymore.