Use an IIFE to Create a Module - what is the point of this pattern?


I am doing the title-described task, and I am wondering what is the point of this pattern. I have read some of the topics here on the subject but none addressed my doubts totally. I will be glad for some further explanation.

As you can see bellow I have 2 patterns, both of them work, but FCC and people seem to recommend the first one, because it’s not polluting the “global namespace”. I wonder, how does it pollute global namespace when in both cases both functions are available only by refferencing the variable “funModule”? So how is this polluting and what exactly?

Are there any more adventages for the firsrt pattern in comparison to the second, apart the forementioned and apart the fact that we can add some code to execute before the “return” statement(where is this useful btw)?

When to use the first and when the second of patterns?

Regards


// let funModule = (function() {
//   return {
//     isCuteMixin: function(obj) {
//       obj.isCute = function() {
//         return true;
//       };
//     },
//     singMixin: function(obj) {
//       obj.sing = function() {
//         console.log("Singing to an awesome tune");
//       };
//     }
//   }
// })();

let funModule = {
isCuteMixin: function(obj) {
  obj.isCute = function() {
    return true;
  };
},
singMixin: function(obj) {
  obj.sing = function() {
    console.log("Singing to an awesome tune");
  };
}
};


var duck = {};
funModule.singMixin(duck);

duck.sing();

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36.

Challenge: Use an IIFE to Create a Module

Link to the challenge:

Hey @tkozuch,

JavaScript is a Garbage Collector language, which means, if there is something in the code that is not needed by the rest of the runtime, it will destroy it so it can free up some memory.
Here’s more about garbage collection:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#garbage_collection

By using an object, it is always going to referencing the actual object, which means it will not go out of the scope, thus the garbage collector will not destroy this. By using an IIFE, the function does not have a name, and the only time it’s referenced is when it returns something. This means after it’s done its job, it will be destroyed to save some memory and keeping the global namespace clear of object names…

Here’s a stack overflow question about this:

Hope this helps :slight_smile:

2 Likes