IIFEs are useful for using closures to hold references to "private" variables. They might be used to prevent others from modifying values you want to protect, or to hold the result of a computation that only needs to be done once (or occasionally) but is frequently used by the function.
e.g. to get the text of an element you might write:
function getText(el) {
if (typeof el.textContent == 'string') {
return el.textContent;
} else if (typeof el.innerText == 'string') {
return el.innerText;
}
}
but to avoid having to do the test every time, an IIFE can be used and the test performed just once:
var getText = (function() {
var d = document.createElement('div');
if (typeof div.textContent == 'string') {
return function (el) {
return el.textContent;
};
} else if (typeof div.innerText == 'string') {
return function (el) {
return el.innerText;
};
}
}());
So the test is only performed once. You can also keep a reference to the global object using a similar strategy:
var someFn = (function (global) {
// in here, you are certain that global references the global object
return function() {
// and in here too
};
// And here's where it comes from
}(this));