Immediately Invoked Function Expression In JavaScript

Introduction

Have you ever imagined writing a function that will get executed immediately after it is created without invoking it? If not then get ready to see the magic!

Javascript allows a function to be called immediately after it is created without even invoking it. It is called Immediately Invoked Function Expression. 
 
Syntax
  1. var object = (function/*arguments(if any)*/ )  
  2. {  
  3.     /*code to be executed*/  
  4.     /*return ifany */  
  5. })( /*arguments(if any)*/ );  
Example

Lets see a normal function in javascript,
  1. var add = function() {  
  2.     var i = 0  
  3.     console.log("inside add");  
  4.     return i + 5;  
  5. };  
  6. console.log("add is not called yet");  
  7. console.log(add());  
as you can see in the above example "add()" will get invoked only when it is explicitly invoked in the last line.
so the output of the above code will be,
 
add is not called yet
inside add
5
 
But if you will make some modifications in the above example then it can be coverted to a IIFE (Immediately Invoked Function Expression
 
Let's do it !!!
  1. var add = (function() {  
  2.     var i = 0  
  3.     console.log("inside add");  
  4.     return i + 5;  
  5. })();  
  6. console.log("add is not called yet");  
  7. console.log(add);  
  8. //console.log(add());  
Following are the modifications I have made to make it a IIFE.
  1. Enclosed the whole anonymous function in brackets "()" 
  2. At the end of the anonymous function I have added () which will call the same function(like we call any other function)
  3.  You can pass any argument in the brackets "()" if you want. that will be input arguments for the function.
Let's see the output
 
inside add
add is not called yet
 
As you can see "inside add" got printed before "add is not yet called".

You might have noticed one more thing here.

I have commented the "console.log(add())" line. as it will give error. Once IIFE gets executed it returns the ouput and it gets stored in the variable. so using a variable like function will give error.

If there is IIFE which you don't want to return anything then it can be writen directly without assigning it a variable also.
 
Conclusion

IIFE is mostly used while creating frameworks or libraries or doing tree structures. These are one-time executing anonymous methods. It is a design pattern also known as Self-Executing Anonymous Functions. 
 
Please let me know your valuable feedbacks/questions.