8

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!!

Community
  • 1
  • 1
Praveen Prasad
  • 31,561
  • 18
  • 73
  • 106

2 Answers2

7

What you will see is something like this:

(function(undefined) {
    /* lots of code */
}());

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 variable undefined is in fact the Javascript primitive value undefined.

So why do you want to do this? Well, the problem is that you can actually create a variable with the name undefined and set it to anything you like, e.g.:

var undefined = 'some text';

A test myvalue === undefined within your code would then have unexpected results.

The anonymous function with the parameter called undefined essentially "resets" the value of undefined to the primitive value, so that you can check against it if you wish without having to worry about whether it has the right value.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
6

Its to make sure undefined is actually undefined. Paul Irish calls it the asshole effect, other js included on the page could change the meaning of undefined, and then you will get unexpected results.

jamcoupe
  • 1,422
  • 1
  • 19
  • 31
Loktar
  • 34,764
  • 7
  • 90
  • 104
  • 1
    I never quite understood it. I could also do something silly like `jQuery = {}`, and then jQuery would stop working - not surprising. If you want to shoot yourself in the foot by putting `undefined = true`, why stop you? – Andrea Mar 01 '11 at 15:38
  • 1
    Well someone else could try shooting you in the foot, like a random plugin your including. – Loktar Mar 01 '11 at 15:40