Object Oriented Programming: Use an IIFE to Create a Module

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

I don’t understand the purpose of using an IIFE in the context provided in the example. It writes:

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!”);
};
}
}
}) (); // The two parentheses cause the function to be immediately invoked

But can’t the same result be achieved without the 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!”);
};
}
};

Either way, motionModule.mixin(obj) works. So what’s the point of the IIFE?

1 Like

IIFE will help prevent global variables to happen. Before the introduction of ES6, JavaScript only had var to declare variables. But this is function scoped instead of block scoped so it could easily contaminate namespace of your app.

Here is an article to give you more insight.

2 Likes

Thank you, that article was very helpful.