Immediately invoked function expressions
IIFEs (immediately invoked function expressions) are a neat code pattern originally popularised by JavaScript, which, however, seem to be less common of in other languages.
An IIFE is basically an inlined function expression that is executed right away. You can use this technique not just in JavaScript, but in all languages where functions are first-class citizens.1
const theAnswer = (() => { return 42; })();
In JavaScript, the syntax recipe is:
- Create an anonymous function:
() => { ... }
- Wrap it in parentheses:
(() => { ... })
- Invoke the function right away:
(() => { ... })()
I find myself using IIFEs regularly for initializing constants that have a non-trivial initialization procedure. For example:
// Try to restore previously stored settings.
// Fall back to default settings on error.
const settings = (() => {
try {
return retrieveSettings();
} catch(e) {
console.error(e);
return defaultSettings;
}
})();
The advantages of IIFEs are:
- Even if the initialization procedure has intermediate states, the final result can still be assigned to an immutable variable in one atomic operation.
- You can fling transient helper variables around without polluting the enclosing scope.
- You still have access to all variables of the enclosing lexical scope.
Alternative implementation approaches would be to split out the initialization procedure into a separate function, or to use mutable variables. Both, however, may not always be desired.
-
Other languages may have slightly different syntax requirements. There are also dedicated idioms in some languages, e.g. block expressions in Rust or
run
functions in Kotlin. ↩︎