Skip to main content

IIFE

A self-invoking function (IIFE - Immediately Invoked Function Expression) is a function that is created and invoked right away, without a separate call by name.


Syntax:

javascript
(function () { console.log('I ran right after being declared!'); })();

Notice the two pairs of parentheses:

  1. The first (function() { ... }) - turns the function into a function expression.
  2. The second () - immediately invokes that function.

Example with parameters:

javascript
(function (name) { console.log(`Hello, ${name}!`); })('Tim');

Prints:

javascript
Hello, Tim!

What IIFE is used for

1. Creating an isolated scope

IIFE is often used to avoid variable conflicts - for example, when writing code that should not "pollute" the global scope (window or global).

javascript
(function() { const secret = 'Secret inside the function'; console.log(secret); })(); console.log(secret); // ReferenceError: secret is not defined

The secret variable is only accessible inside the IIFE.


2. One-time code initialization

You can use an IIFE to run something once, on load:

javascript
const config = (() => { const apiKey = '12345'; const baseUrl = 'https://api.example.com'; return { apiKey, baseUrl }; })(); console.log(config.apiKey); // 12345

We return an object, but the variables inside stay encapsulated.


3. Use with async / await

An IIFE can be made asynchronous to use await at the top level:

javascript
(async () => { const data = await fetch('/api/data').then(res => res.json()); console.log(data); })();

Historically

Before ES6 modules appeared (where every import/export file unit now has its own scope), IIFEs were actively used in JavaScript for encapsulation and code structuring. They are used less often now, but are still useful for:

  • one-time initialization,
  • isolating temporary variables,
  • immediately running async code.

In short:

TraitDescription
NameIIFE - Immediately Invoked Function Expression
EssenceThe function is created and invoked right away
WhyIsolation, initialization, temporary variables
TraitsDoes not pollute the global scope, can be async

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.