Need a function to run once, right where you define it? An immediately invoked function expression (IIFE) creates a function value and calls it in the same construct. It is useful when the work needs its own scope but the function itself does not need a lasting name. section 3.3.1 section 11.3
Create it, then call it
(function () { // Run this work now. })(); The final () invokes the function. The surrounding parentheses put the function in an expression position; the expression to the left of a call need not be a function name. A function expression may also have a name. section 3.3.1
An IIFE creates a local scope. Variables declared inside it are not visible outside, which helps avoid unnecessary globals. A function created inside can still use those variables through a closure after the IIFE finishes. That pairing made IIFEs especially useful for modules before built-in ES6 modules. section 11.1.1 section 11.3
A small module
const counter = (function () { let clicks = 0; return { countClicks: function () { return ++clicks; } }; })(); The call returns an object that becomes the public interface. Its method can use clicks, but outside code cannot access clicks directly. The same pattern can attach a browser event listener while keeping its counter private. section 11.1.1
(function(){
const PROPERTIES = {
position: "absolute",
visibility: "hidden",
display: "block"
};
window.getDimensions = element => {
const previous = {};
for (let key in PROPERTIES) {
previous[key] = element.style[key];
element.style[key] = PROPERTIES[key];
}
const result = {
width: element.offsetWidth,
height: element.offsetHeight
};
for (let key in PROPERTIES) {
element.style[key] = previous[key];
}
return result;
};
})();
A DOM utility uses an IIFE to keep temporary style settings out of the global namespace while exposing a dimension-measuring function through window. section 12.3.5
Keep the two jobs distinct:
- The immediate call runs setup and establishes a local scope. section 3.3.1 section 11.3
- Closures keep selected local state available to functions that survive that call. section 11.1.1
- A returned object can expose selected operations without exposing the internal variables themselves. section 11.1.1


