logologo

Three-D

☕Sign in

    Recent Post:

    Categories:

    nextjsjavascriptthreejshonoreactjs
    featured post image

    snippets

    featured post image

    What is Currying?

    featured post image

    What is an IIFE?

    What is an IIFE?

    September 22, 2024

    510

    image

    Think you know it all?

    Take quiz!

    An IIFE (Immediately Invoked Function Expression) is a function that is executed immediately after it is defined. It helps create a local scope and avoid polluting the global namespace. IIFEs are often used to encapsulate code and avoid variable collisions.

    Structure of an IIFE

    An IIFE is defined by wrapping the function declaration in parentheses, followed by another pair of parentheses to invoke it.

    code

    (function() {
        console.log("This is an IIFE!");
    })();

    The function is wrapped in parentheses to convert it into an expression. The () at the end immediately invokes the function.

    IIFE with Parameters

    You can also pass parameters to an IIFE.

    code

    (function(name) {
        console.log("Hello, " + name + "!");
    })("Satyendra");

    The IIFE takes a parameter name, and the argument "Satyendra" is passed when invoking it.

    Benefits of Using IIFE

    Encapsulation: IIFEs create a local scope, keeping variables and functions private. Avoiding Global Namespace Pollution: Variables defined inside an IIFE are not accessible from the outside, helping prevent conflict

    Example of IIFE in Practice

    You might use an IIFE to create a module-like structure.

    code

    const myModule = (function() {
        let privateVariable = "I am private";
    
        return {
            getPrivate: function() {
                return privateVariable;
            }
        };
    })();
    
    console.log(myModule.getPrivate()); // Output: I am private
    console.log(myModule.privateVariable); // Output: undefined

    The variable privateVariable is not accessible outside the IIFE, ensuring that it remains private.

    Self-Invoking Functions

    The term "self-invoking function" typically refers to the same concept as an IIFE. Both describe a function that runs immediately upon creation.

    However, "self-invoking" can also refer to any function that calls itself (recursion). This can create confusion, so it's important to clarify the context.

    Summary

    An IIFE is a function that is executed immediately after its definition, providing a local scope and avoiding global namespace pollution.

    It can accept parameters, making it versatile for various applications.

    IIFEs are useful for encapsulating code and creating modules.