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?
Adding numbers to undefined results in NaN (not-a-number), which won't get you anywhere.
An undefined variable in the source code of a computer program is a variable that is accessed in the code but has not been declared by that code. In some programming languages, an implicit declaration is provided the first time such a variable is encountered at compile time.
It means that JavaScript copies the values of the variables into the function arguments. Any changes that you make to the arguments inside the function do not reflect the passing variables outside of the function.
See, undefined is passed as argument, but not passed as a parameter when we invoke the function. So, inside the function the value of the variable undefined is (guaranteed) the original value of undefined .
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.
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