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?
There are two reasons for that:
1) If
undefinedis 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*,
undefinedwas 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: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 isundefinedso 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,NaNandInfinitybecame 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.