IIFE vs normal OBJS;

So, I was doing the referenced lesson and a doubt came to my mind, what is the difference between using a IIFE module instead of just declaring straightforward the method as I did in the code below:


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

Challenge: Use an IIFE to Create a Module

Link to the challenge:

1 Like

Hey @karellen,

I don’t know much about modules, but AFAIK, IIFE is encapsulating, that means it only return the object and not anything inside it. So it’s like having another file with different functions, and you can only use certain parts of it that is public. IIFE is also immediately invoked, this means, it can be used ASAP. IIFE is still used for JS modules, but there is now ES6 modules, where you can export and import files. IIFE is like the old day’s of JavaScript ES6 Classes modules.

IIFE modules are also anonymous/unamed until assigned, this means that it doesn’t clutter the global namespace. An example is the JQuery module, if you look closer, it uses IIFE to declare it’s module, and everytime you log the object, it is only 1 namespace with a lot of properties (jquery.fn.) or ($.fn.).

Here’s more example:

Normal Obj:

let MyModule = {
  private_value1: 'Hello World',
  doSomething1: function() {
    return private_value1;
  }
}

//Using object, you can access everything the object has so
console.log(MyModule.private_value1) // Will output 'Hello World'

While IIFE:

let MyModule = (function() {
   let private_value1 = 'Hello World'

   return {
     doSomething1: function() {
         return private_value1;
    }
   }
})()

// By using IIFE, you cannot access the properties 
// that is not returned...

console.log(MyModule.private_value1) // Outputs undefined

I guess the curriculum challenge didn’t really explain the benefits. Well I hope this helps you to understand a little bit more…