While viewing jQuery’s uncompressed source code I stumbled upon something I don’t quite understand. When the create their anonymous function, they place undefined as a 2nd argument. What is this doing, and why are they using undefined? Is it necessary to put undefined as an argument in an anonymous function? Below is an example of what I am talking about.
(function( window, undefined) {
...code here
})( window );
What this is doing, is reassigning
undefinedtoundefinedinside that closure. Thats a failsafe. Because other code may accidentally do something likeAnd thats valid in javascript(if the JS engine being used has not implemented ECMAScript 5 specification, in ECMAScript 5 spec
undefinedis nonnon-writable, MDN DOC ),Quote from MDN New_in_JavaScript 1.8.5 (ECMA 5) Page
And from
ES5 Annotated Specin GuthubES5 spec Sectionx15.1.1.3Even if
global undefinedis not writable You can have a local variable namedundefinedand can mess up your code(mainly comparisons withundefined). But that’s your responsibility. You can have codes likeDemo: http://jsfiddle.net/joycse06/V4DKN/
However if
undefinedis writeable then the above assignment may hamper manycomparisonmade withundefinedafter that line of code asundefinedis notundefinedanymore. It has some value now.So as they are calling that anonymous function like
And receiving
That means inside that closure
undefinedis restored toundefined, as it has not been passed any value thus securing use ofundefinedinside that anonymous function.A very good detailed article on this http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/
I am quoting some lines from the above article link to make things clear
What is undefined?
In JavaScript there is Undefined (type), undefined (value) and undefined (variable).
Undefined (type) is a built-in JavaScript type.
undefined (value) is a primitive and is the sole value of the Undefined type.
Any property that has not been assigned a value, assumes the undefined value. (ECMA 4.3.9
and 4.3.10).
A function without a return statement, or a function with an empty return statement returns undefined. The value of an unsupplied function argument is undefined.
undefined (variable) is a global property whose initial value is undefined (value), Since its a global property we can also access it as a variable. For consistency I’m always going to call it a variable in this article.
As of ECMA 3, its value can be reassigned :
Needless to say, re-assigning values to the undefined variable is very bad practice, and in fact its not allowed by ECMA 5.