IIFE - Immediately Invoked Function Expression In JS

An IIFE, or Immediately Invoked Function Expression, is a function that is defined and immediately executed. It is a popular pattern in JavaScript that is often used to create a private scope for variables or to create a self-contained module.

To create an IIFE, you define a function using the function keyword, followed by a set of parentheses and a set of curly braces. You then immediately invoke the function by appending another set of parentheses after the closing curly brace.

Here's an example,

(function() {
    console.log('Hello, World!');
})();

Inside the IIFE, you can define variables and functions that are only accessible within the IIFE. This can be useful for creating private variables or for creating self-contained modules that can be imported and used in other parts of the application.

Here's an example of an IIFE that creates a self-contained module,

const myModule = (function() {
    // Private variables and functions
    let secret = 'This is a secret';

    function doSomething() {
        console.log('Doing something...');
    }
    // Public API
    return {
        sayHello: function() {
            console.log('Hello, World!');
        },
        doSomething: doSomething
    };
})();
// Use the module
myModule.sayHello(); // 'Hello, World!'
myModule.doSomething(); // 'Doing something...'
console.log(myModule.secret); // undefined (secret is a private variable)

In this example, the IIFE defines a secret variable and a doSomething function that are only accessible within the IIFE. It also defines a public API that consists of a sayHello function and the doSomething function.

The public API is returned from the IIFE and can be used by other parts of the application.

Ebook Download
View all
Learn
View all