Possible Duplicates:
How does this JavaScript/JQuery Syntax work: (function( window, undefined ) { })(window)?
What advantages does using (function(window, document, undefined) { … })(window, document) confer?
i have seen many javascript libraries create a variable named “undefined”, iam unable to figure out its purpose, below are lines copied from jQuery library
* Date: Wed Feb 23 13:55:29 2011 -0500
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {
Please suggest me the reason and benefits of doing so!!
What you will see is something like this:
This creates an anonymous function and immediately executes it. The function has a parameter called
undefined. Since there is no argument passed to the function, the variableundefinedis in fact the Javascript primitive valueundefined.So why do you want to do this? Well, the problem is that you can actually create a variable with the name
undefinedand set it to anything you like, e.g.:A test
myvalue === undefinedwithin your code would then have unexpected results.The anonymous function with the parameter called
undefinedessentially “resets” the value ofundefinedto the primitive value, so that you can check against it if you wish without having to worry about whether it has the right value.