Using an IIFE to Create a Module

With IIFE:

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!");
      };
    }
  }
})();

Without IIFE:

let motionModule = {
  glideMixin: function(obj) {
    obj.glide = function() {
      console.log("Gliding on the water");
    };
  },
  flyMixin: function(obj) {
    obj.fly = function() {
      console.log("Flying, wooosh!");
    };
  }
};

The challenge suggests that an IIFE be used to create the module. These two pieces of code seem equivalent to me, except the latter is simpler. Why is an IIFE needed? Am I missing something?

Why is an IIFE needed? This module is suppose to teach you about, IIFE.
Of course you don’t have to use it our could use an alternative but, simply knowing of it exsitence could already be of help to you. In case you might end up with a simulair problem that could require IIFE.
I also would recomend you to Google IIFE and look into more options who know what it might be used for some day :3

1 Like

Just Googling doesn’t immediately shed a lot of light on the situation.

Here is a good description with a lighthearted explanation.

TL;DR
An Immediately Invoked Function Expression is a good way at protecting the scope of your function and the variables within it.

1 Like

The difference is mainly scope control and that you can pass arguments to it when invoked.

Learning JavaScript Design Patterns: The Module Pattern

3 Likes

@JeremyLT This succinct definition is enlightening. It is clear to me now why such an expression may be helpful. Thank you~!

1 Like

I’m glad the description helped!