Immediately Invoked Function Expression (IIFE)

IIFE (pronounced as iffy) is an anonymous function which is immediately invoked. We don’t have to call this function separately.

Here is the syntax:

(function(){

    // some code

}());

The last ( ) actually invokes the function.

One of the uses of IIFE is that we can make sure, there are no global variables in our script.

Here are two examples, one normal and second with IFFE.

first.htm

In this example, result will become a global variable if mixed with other scripts.

<html>
  <head>
     <script type="text/javascript">
         var result;    // global variable

         var sum = function(a,b){
            result = a+b;
         };
 
         sum(5,6);
         alert(result);
     </script>
 </head>

<body>

  You should see an alert

</body>
</html>

second.htm

In this example, there will not be any global variable. Everything is inside the scope of anonymous function.

<html>
   <head>
       <script type="text/javascript">
          (function(){
              var result;

              var sum = function(a,b){
                   result = a+b;
              };

              sum(5,6);

              alert(result);
           }()); 
       </script>
 </head>

<body>

You should see an alert

</body>
</html>