I see javascript libraries set up like this:
(function (global, undefined) {
//..
})(this)
What is the meaning of undefined
in this context?
I see javascript libraries set up like this:
(function (global, undefined) {
//..
})(this)
What is the meaning of undefined
in this context?
In older browsers, undefined
wasn't immutable or non-writable. Setting undefined
as a name for an unused function parameter meant that it was undefined, even if it got set in a higher scope.
// Old browser
undefined = 1;
undefined; // 1
// Modern browser
undefined = 1;
undefined; // undefined
It should be noted that the non-writability is only applicable in the global scope, in both cases the following is true;
(function () { // creating a new scope means..
var undefined = 1; // this is now different to the `undefined` global
return undefined; // so can be written to, e.g. set as 1
}()); // 1
Setting undefined
as a parameter of the function allow minifiers to replace it by a shorter name.
For example this:
(function (global, undefined) {
alert(undefined)
})(this)
May be minified to this:
(function(a,b){alert(b)})(this)
So all occurrences of the undefined
variable inside the function will be renamed to some short name like b
. Irrespective of the variable name, it'll have the same value, and so will serve the same purpose.