Immediately invoked function expressions
2 min. read

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:

  1. Create an anonymous function: () => { ... }
  2. Wrap it in parentheses: (() => { ... })
  3. 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:

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.


  1. 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. ↩︎

My e-mail is:
Copy to Clipboard