Online courses in ASP.NET MVC, ASP.NET Core, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC / Core, jQuery, Angular, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Quick Introduction to Immediately Invoked Function Expressions & Closures

Modern web applications heavily rely on JavaScript and JavaScript frameworks. That's why ASP.NET developers need to be aware of JavaScript concepts such as Immediately Invoked Function Expressions (IIFE) and Closures. To that end this article presents a quick introduction to these two features.

Immediately Invoked Function Expressions (IIFE)

An immediately invoked function expression is a JavaScript function that is executed immediately after it is created. Usually you create a named or anonymous JavaScript function and then somewhere in the code you call that function. Consider the following code:

function HelloWorld() {
    alert("Hello World!");
}

var myfunction = function () {
    alert("Hello World!");
}

HelloWorld();
myfunction();

Here, the code creates a named function called HelloWorld(). The code also creates an anonymous function and stores it in a variable - myfunction. The code then proceeds to call these two functions. That means function creation and function execution are two distinct steps.

Using IIFE you can create and run a function immediately. The following syntax shows how:

(function () {
    alert("Hello World!");
})();

As you can see, the above code creates an anonymous function. The whole function is enclosed in brackets and is immediately followed by (). This way function creation and execution are combined. The function can take parameters just like any other JavaScript function.

(function (msg) {
    alert(msg);
})("Hello World!");

Now the function takes msg parameter. While invoking the function a value of Hello World! is passed to the function.

If you ever created a jQuery plugin you will find that many of them use IIFE pattern. Consider the following jQuery plugin:

(function ($) {
    $.fn.myPlugin = function (settings) {
       //plugin code here
    }
})(jQuery);

As you can see, this template for a jQuery plugin consists of an anonymous function that takes a single parameter - $ ($ is a valid variable name in JavaScript). The actual code of the plugin goes inside the inner anonymous function (the one that is assigned to myPlugin ).

The outer function is immediately executed by passing jQuery object to it as a parameter. This way all the inner code of the IIFE refers to the jQuery object as $. This pattern ensures that the meaning of $ is preserved for all the inside code.

JavaScript Closures

 Simply put a closure is an inner function that has access to the parameters and variables defined in the outer function. Moreover, this environment is preserved even if the outer function returns.

The following code will make this clear:

function Outer(msg) {

    function Inner() {
        alert(msg);
    }

    Inner();
}

Outer("Hello World!");

Here, the outer function accepts msg parameter. The msg parameter is used by the inner function and is displayed using an alert. Then the outer function calls the inner function. The external code then invokes the outer function (external code won't have access to inner function).

Now let's see a bit complex usage of closures.

function Outer() {
    var msg = "";

    var obj = {};
    obj.setMsg = function (val) {
        msg = val;
    };
    obj.getMsg = function () {
        return msg;
    };

    return obj;
}

var result = Outer();
result.setMsg("Hello World!");
alert(result.getMsg());

Here, the Outer() function defines a variable - msg - in it's private scope. Then a JavaScript object is created and two function properties are added to it - setMsg() and getMsg(). The setMsg() function assigns a new value to the msg variable. The getMsg() returns the value of msg to the caller.

The obj is returned to the caller. At this stage the Outer() returns. Since Outer() has returned, ordinarily you would expect msg variable to go out of scope. However, result.setMsg() and result.getMsg() still work as expected. This indicates that even if the function has returned the environment has been preserved.

Closures are widely used in jQuery as well as AngularJS to organize the code.

More information about IIFE and Closures can be obtained here and here.




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 19 Oct 2015



Tags : ASP.NET Web Forms MVC jQuery JavaScript