What is an Immediately Invoked Function in JavaScript?

An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. This article explains IIFEs in detail, their syntax, use cases, and benefits.

What is an IIFE?

An Immediately Invoked Function Expression (IIFE) is a function that is executed right after it is created. The primary purpose of an IIFE is to create a new scope and avoid polluting the global scope.

Syntax of an IIFE

An IIFE can be written in two main ways:

  1. Using the traditional function syntax:
;(function () {
  console.log('This is an IIFE')
})()
  1. Using the arrow function syntax (introduced in ES6):
;(() => {
  console.log('This is an IIFE using arrow function')
})()

In both cases, the function is defined and then immediately invoked.

Why Use an IIFE?

IIFEs are used for several reasons:

  1. Avoiding Global Variables: By wrapping code inside an IIFE, variables and functions can be kept within the local scope of the function, avoiding global namespace pollution.

  2. Creating a New Scope: IIFEs can be used to create a new scope, which can be useful for encapsulating code and avoiding variable name conflicts.

  3. Initialization Code: IIFEs are often used for initialization tasks that need to be executed once and do not need to be repeated or accessed later.

Example of Avoiding Global Variables

Consider the following example where variables are encapsulated within an IIFE:

;(function () {
  var localVar = 'I am local'
  console.log(localVar) // I am local
})()

console.log(localVar) // Uncaught ReferenceError: localVar is not defined

In this example, localVar is not accessible outside the IIFE, thus avoiding any potential conflicts with other variables in the global scope.

Example of Initialization Code

IIFEs are also useful for running initialization code:

const app = (function () {
  const config = {
    apiKey: 'your-api-key',
    apiUrl: 'https://api.example.com',
  }

  function initialize() {
    console.log('App initialized with config:', config)
  }

  initialize()

  return {
    getConfig: () => config,
  }
})()

console.log(app.getConfig()) // { apiKey: 'your-api-key', apiUrl: 'https://api.example.com' }

Here, the IIFE initializes the app module and returns an object with a method to access the configuration.

IIFE Patterns

IIFEs can be used in various patterns to achieve different results. Here are a few common patterns:

Using IIFE with Parameters

IIFEs can accept parameters, which allows for more flexible and reusable code:

const result = (function (a, b) {
  return a + b
})(5, 10)

console.log(result) // 15

Creating Private Variables

IIFEs can be used to create private variables and methods:

const counter = (function () {
  let count = 0

  return {
    increment: () => ++count,
    decrement: () => --count,
    getCount: () => count,
  }
})()

console.log(counter.getCount()) // 0
counter.increment()
console.log(counter.getCount()) // 1
counter.decrement()
console.log(counter.getCount()) // 0

In this example, the count variable is private and can only be accessed and modified through the methods exposed by the returned object.

Module Pattern

IIFEs are often used in the module pattern to create modules with private and public members:

const myModule = (function () {
  let privateVar = 'I am private'

  function privateMethod() {
    console.log(privateVar)
  }

  return {
    publicMethod: () => privateMethod(),
  }
})()

myModule.publicMethod() // I am private

In this example, privateVar and privateMethod are private, while publicMethod is exposed as part of the module's public API.

Conclusion

An Immediately Invoked Function Expression (IIFE) is a powerful tool in JavaScript that allows you to execute functions immediately and create isolated scopes. By understanding and utilizing IIFEs, you can write cleaner, more modular, and more maintainable code.