JavaScript Experts Help! Why to use IIFE for module instead of directly creating another object?

Tell us what’s happening:

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

The second way doesn’t seem to pollute the global variables 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?)?

Link to the challenge:

This mostly introduces the iife, in a context you’re already familiar with. And you’re seeing how similar it is to an object literal, which is great!

But there is a key difference between the two: because the functions returned by the iife are defined within the scope of that function, they have access to that scope, *even after the iife has completed its execution.

This is a way of creating a private namespace within the function which the object returned can continue to access. Objects traditionally do not have private properties, everything is exposed - but a closure gives us private variables and a public interface, which a plain object couldn’t.

The newer ES standards include a mechanism for defining private properties, but iifes and modules and factory functions are still a valuable tool.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.