The reason for method # 2 is that you will find code inside IIFE that returns something (usually, but not necessarily, an object or function). What IIFE returns is what ends with the assignment. For instance:.
//IIFE Immediately Invoked Function Expression assigned to doStuff variable var doStuff = (function () { var privateInformationForDoStuff = 0; function doStuff() { console.log(++privateInformationForDoStuff); } return doStuff; }());
Here the variable ends with a reference to a function, which each time it is called gives us a number higher than in the previous time. IIFE exists to ensure that nothing can change the privateInformationForDoStuff variable, it is completely closed to the doStuff function.
A common use of this is to create objects with various functions on them, sometimes called modules, which can also have personal information that is available only in the "module":
var MyApp = (function() { var privateModuleInformation; var morePrivateModuleInformation;
source share