JavaScript 101: Immediately Invoked Functions

JavaScript 101: Immediately Invoked Functions

· 3 min read
javascript fundamentals functions

tl;dr Like it says on the tin, an immediately invoked function (IIFE) is a function that is executed as soon as it is defined. No waiting around, no messing about. Straight to business.

Prerequisites

  • Understanding of hoisting (or at least a vague idea)
  • Comfort with functions in general
  • Brackets. Lots of brackets. So many brackets
  • A llama for emotional support during the parenthesis overload

IIFE’s main use cases are for when we don’t want to pollute the global namespace. As in, we don’t want to introduce a bunch of variables and functions into a “scope” accessible by the rest of our application. You can also use IIFE if you want to make use of the module pattern.

IIFE Syntax

(function () {
  // ...
})();

To understand what’s going on here we need to understand how function declarations and function expressions work in Javascript (see Hoisting).

When Javascript is running code inside the execution context, it recognises the functions that are declared, and functions that are expressed.

function declared(){
    // ...
}

const expressed = () => { // ... }

In Javascript, parenthesis acts as a grouping operator in that Javascript will attempt to keep whatever is in between those brackets together. When a function is included within the brackets then Javascript knows to treat this function as independent from anything around it. This also means the function is only able to act upon its own scope. Its like when you go into a separate room to take a phone call. You can do whatever you want in there but nobody else knows about it.

You also don’t have to provide an IIFE with a name, this also makes an IIFE an anonymous function. Mysterious.

n.b: you can also write IIFEs using the arrow syntax:

((x) => {
 // ...
})('value')


((x) => {
    var z  = x
 console.log(x)
})('value')

((y) => { console.log(y) console.log(z) })('another value')

When would you actually use one of these?

Good question. Here’s a few scenarios:

  • Avoiding global variable pollution: You’ve got some setup code that needs to run once and you don’t want its variables hanging around like that one guest who won’t leave the party
  • Creating private scope: When you need variables that absolutely nobody else should mess with
  • Module patterns: Before ES6 modules were a thing, this was how people did encapsulation
  • Running async code at the top level: Sometimes you need an async IIFE to use await outside of an async function
(async () => {
  const data = await fetch('/api/llamas');
  console.log(data); // llama data, obviously
})();

Further Reading

Available for rescue and re-platforming work

I take over platforms that already exist and are in trouble. Node, TypeScript, React and Laravel, mostly in regulated or high-traffic environments. If something needs rescuing, re-platforming or finishing, my full history is on the CV.

Related Posts

Call, Bind and Apply

javascript fundamentals

Three ways to tell a function what ’this’ is supposed to mean.

Javascript 101: Hoisting

javascript fundamentals

What JavaScript does with your declarations before it runs a single line.

Comments