"Use an IIFE to Create a Module" - why?

Tell us what’s happening:

What’s the point of using an IIFE to create a module instead of declaring the module methods directly in the module?

Your code so far

// The lesson presents this as an example..
let motionModule = (function () {
  return {
    glideMixin: function (obj) {
      obj.glide = function() {
        console.log("Gliding on the water");
      };
    },
    flyMixin: function(obj) {
      obj.fly = function() {
        console.log("Flying, wooosh!");
      };
    }
  }
}) ()

// ...but why not use this instead?
let motionModule = {
  glideMixin: function (obj) {
    obj.glide = function() {
      console.log("Gliding on the water");
    };
  },
  flyMixin: function(obj) {
    obj.fly = function() {
      console.log("Flying, wooosh!");
    };
  }
}

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module

The benefit of using an IIFE is that it frees you up to do preparations before assigning things to the return object.

1 Like

Can you expand on that please? I read that if you use IIFE, the module will be function scoped. But why is it matter when I can access motionModule's flyMixin using motionModule.flyMixin in @Semaviro’s both examples?

While it’s not obvious in that example, the point is that you can stick more code above the return statement. Its useful when making large modules so that you don’t pollute global namespace with helper functions and it even allows the module to chose the global object on the fly instead of hardcoding it (which varies between Node and the browser). E.g. the entire jQuery library is wrapped in an IIFE.

2 Likes

Thanks dude! I think I got the gist of it.