Skip to content

JavaScript 101: Immediately Invoked Functions

by David Yates

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.

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(https://javascript.plainenglish.io/data-hiding-with-javascript-module-pattern-62b71520bddd).

IIFE Syntax:

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

To understand whats going on here we need to understand how function declarations and function expressions work in Javascript (see Hoisting(/code/javascript/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.

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

n.b: you can also write IIFE’s using the arrow syntax:

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


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

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

Further Reading

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

https://javascript.plainenglish.io/data-hiding-with-javascript-module-pattern-62b71520bddd

All Posts