Why use IIFE to create a module instead of directly creating an object containing the functions in the module?

Tell us what’s happening:

Hey! I’m confused about what’s the difference between using IIFE (immediately invoked function expression) and just declaring functions in a module object. For example:

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

Directly creating a module object

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

So…

The second way doesn’t seem to pollute the global namespace and it even pass the tests, so why is the lesson guiding us to create a module using IIFE (or is it just to present IIFE?)? To me, it’s more verbose.
Any help appreciated!

Your browser information:

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

Link to the challenge:
Can’t post links yet. It’s the last challenge from Object Oriented Programming in Javascript Algorithms And Data Structures Certification

1 Like