Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable named undefined in Javascript Libraries [duplicate]

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

like image 587
Praveen Prasad Avatar asked Mar 01 '11 15:03

Praveen Prasad


2 Answers

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.

like image 145
lonesomeday Avatar answered Oct 08 '22 08:10

lonesomeday


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.

like image 32
Loktar Avatar answered Oct 08 '22 06:10

Loktar