What advantages does using (function(window, document, undefined) { … })(window, document) confer? [duplicate]

Why are window and document being fed in instead of just being accessed normally?

Generally to fasten the identifier resolution process, having them as local variables can help (although IMO the performance improvements may be negligible).

Passing the global object is also a widely used technique on non-browser environments, where you don’t have a window identifier at the global scope, e.g.:

(function (global) {
  //..
})(this); // this on the global execution context is 
          // the global object itself

Why the heck is undefined being passed in?

This is made because the undefined global property in ECMAScript 3, is mutable, meaning that someone could change its value affecting your code, for example:

undefined = true; // mutable
(function (undefined) {
  alert(typeof undefined); // "undefined", the local identifier
})(); // <-- no value passed, undefined by default

If you look carefully undefined is actually not being passed (there’s no argument on the function call), that’s one of the reliable ways to get the undefined value, without using the property window.undefined.

The name undefined in JavaScript doesn’t mean anything special, is not a keyword like true, false, etc…, it’s just an identifier.

Just for the record, in ECMAScript 5, this property was made non-writable…

Is attaching the object we’re creating directly to window a particularly good idea?

It’s a common way used to declare global properties when you are on another function scope.

Leave a Comment