Open In App

What is the (function() { } )() construct in JavaScript?

If you’ve ever played around with JavaScript, you might have seen this expression. It’s like a strange set of symbols, but it has a special name that is an immediately invoked function expression, or IIFE. In this article, we will understand each element of the expression as well as the functionalities with the help of examples.

Let’s start with the detailed definition of the expression to understand its functionalities.



(function() { } )() Construct

This expression is immediately invoked function expression. It has two parts – function declaration (function() {}) and invocation (). This (function() {}) defines an anonymous function. This is enclosed by () indicates the function() {} is an expression not just a declaration. The () immediately invokes the function.

Although the (function() { } )() may appear to be an odd combination of curly braces and parenthesis, it has a specific function in JavaScript.



Syntax:

(function() { } )() 

Parameters:

Example 1: In this example, this expression creates a local scope, preventing the counter variable from polluting the global scope. This encapsulation is beneficial, especially in larger applications where avoiding global variable conflicts is crucial.




(function () {
    let counter = 0;
    function increaseCounter() {
        counter++;
    }
    increaseCounter();
    console.log(counter);
})();

Output
1

Example 2: Here, the IIFE is used to create a module with private and public members. The private members (privateVariable and privateFunction) are encapsulated within the IIFE, making them inaccessible from outside the module. The returned object contains only the public members.




let Module = (function () {
    let privateVariable = "I am private.";
 
    function privateFunction() {
        console.log("This is a private function.");
    }
 
    return {
        publicVariable: "I am public.",
        publicFunction: function () {
            console.log("This is a public function.");
        }
    };
})();
 
console.log(Module.publicVariable);
Module.publicFunction();
console.log(Module.privateVariable);
// Module.privateFunction();
// Error: Module.privateFunction is not a function

Output
I am public.
This is a public function.
undefined

Conclusion:

JavaScript’s (function() { } )() construct may look confusing at first, but it’s a very useful tool for writing code blocks that are instantly executed and self-contained. You can prevent contaminating the global namespace and run code exactly when required by enclosing it inside an IIFE. We can write more organized and modular JavaScript code by using the IIFE.


Article Tags :