Why to use IIFE to Create a Module?

Why to use IIFE to Create a Module?
0

#1

I understand the syntax of this challenge but I don’t get the point of using IIFE here.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module/

What is the point of using an IIFE returning an object, if I can just assign an object from the start?

How this:

let moduleName = (function () {
return {"some object with methods"}
}
)();

Is better than this:

let moduleName = {"some object with methods"};

#2

(IIFE) is often used to group related functionality into a single object or module. For example, an earlier challenge defined two mixins:
function glideMixin(obj) {
obj.glide = function() {
console.log(“Gliding on the water”);
};
}
function flyMixin(obj) {
obj.fly = function() {
console.log(“Flying, wooosh!”);
};
}
We can group these mixins into a module as follows:
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

Bluestacks TextNow


#3

You’ll find an excellent answer to your question at this link:
The Module Pattern from JavaScript Design Patterns

IIFE’s are also used in namespacing.

It is worthwhile reading Addy Osmani’s excellent book JavaScript Design Patterns. It is free online.


#4

Thank you. Your links looks useful.
I will take time to read it.


#5

Sorry, but this is not an answer for the question.
The function in your answer returns an object.
My question was why not to use an object from the start.


#6

The important point here is that you don’t want to pollute the global namespace by adding variables to it. If you create an object, you have to name it. In this way you don’t have to name anything, not the function, not the object, the module just consists of a return value (the unnamed object) that can be imported directly by another program.

Sorry I didn’t see the challenge you were referring to, yes in this particular case, the return value will get stored in the global execution contexts which defeats the purpose. However, in a real module example, IIFE are not assigned to a variable in the module, the module is simply the IIFE which gets executed immediately when someone tries to require it/import it and gives it the object.


#7

Thank you. Now it makes sense to me.

I have never wrote a module before, so I am asking just to understand when I might need an IIFE.
I have read that with ES6 modules the problem with global namespaces does not exist any more. Does it mean that IIFE for modules are outdated?


#8

Yes, IIFE for modules is an outdated practice. It was popular before the development of module systems like CommonJS, ES6 modules etc.