2

I saw this scope encapsulation, with the undefined value as 2nd parameter in the jQUery UI source code https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.button.js .As I'm writing a jquery ui plugin, I'm wondering what is the benefit to set undefined in parameter ?

(function( $, undefined ) {
//...
}( jQuery);
Jude Duran
  • 2,195
  • 2
  • 25
  • 41
krampstudio
  • 3,519
  • 2
  • 43
  • 63
  • Good question! I've been wondering about this as well. – Rutwick Gangurde May 24 '13 at 11:56
  • It is used to make sure that undefined really mean undefined i.e. if by mistake somewhere in the code undefined = abc( is assigned a value) then it will render all those if(something === undefined) useless because then you'll be comparing against abc and not undefined. This way, undefined is truly undefined because when invoked (function ($, undefined){...}(jQuery);' $ is assigned jQuery but undefined is never assigned a value. – U.P May 24 '13 at 11:59

2 Answers2

2

This is done, to have a pointer to the "real" undefined value.

In general, in JavaScript you can even modify the value stored under undefined, which in turn breaks many use cases for it.

undefined = 'abc';
var obj = { prop: 'abc' };

if ( obj.prop == undefined ) {
  // do something
  // this is actually called despite the fact, that the property is set!
}

EDIT

As mentioned in the comments by @Christoph this also helps in reducing the code size, when using minifiers. Here the local undefined is treated as a usual variable, which can be minified to, e.g., a possibly and thus reducing the code size.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • This is why you use `typeof obj.prop === 'undefined'`. – SeinopSys May 24 '13 at 11:59
  • 3
    htm5 defines it as readonly. Most modern browsers comply to that. The more relevant reason is that as a variablename it can be minified to a single letter. – Christoph May 24 '13 at 12:00
  • @DJDavid98 you can still overwrite `undefined` in older browsers. – Christoph May 24 '13 at 12:02
  • 1
    This is not entirely correct as it depends on the implementation of ECMA Script and not "HTML5" (starting from ECMAScript 5 undefined is read only). – MMM May 24 '13 at 12:31
1

It creates a local copy of undefined variable for your function which point to actual undefined, so if someone has changed the value of undefined globally , it will not effect your code.

How it works is , as you are not passing the second parameter in your self executing function. So value of undefined variable will be actually undefined.

Sudhanshu Yadav
  • 2,323
  • 18
  • 18