Use an IIFE to Create a Module - Why use IIFE?

Use an IIFE to Create a Module - Why use IIFE?
0

#1

Tell us what’s happening:

Hi, I don’t get why i’d need to use an IIFE to do this challenge. What’s the advantage? The below code works just as well and is cleaner in my opinion. Am I missing something?

Your code so far


let funModule = {
  isCuteMixin: function(obj) {
    obj.isCute = function() {
      return true;
    };
  },
  singMixin: function(obj) {
    obj.sing = function() {
      console.log("Singing to an awesome tune");
    };
  }
};

Your browser information:

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

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


#2

It’s a method of grouping functionality in one common place. In the FCC example in isolation, what you said is true, but you have to look at it as if you have many, many other pieces of functionality and you need a way to organise them in a sensible way. For small scripts and very small applications it doesn’t really matter, but for anything else, some way to organise things is important.

re why use an IIFE: because JS is function scoped, you can contain everything declared to just that function, all the variables etc will be kept there and won’t leak out.

Modules are now built into the language (a file is a module, and you can import/export things from each one), but there isn’t full support everywhere at the minute. You can get the same effect by wrapping a set of common code in an IIFE (so it’s all self contained under one namespace).

Note that this has nothing really to do with OO programming, it’s just a common way of organising code, but it makes sense to introduce the idea at this point in the curriculum

https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

EDIT - this link is probably better

(also, you might notice if you google for ‘js module pattern’ that most of the top-ranked and useful links are from before 2015, this is when modules were added to the language)


Use an IIFE to Create a Module - Why do I need to use IIFE
#3

Thanks for the fast and enlightening reply! From a security perspective, it makes sense to do it through IIFE.
It would have been helpful to have this mentioned in this particular FCC challenge.


#4

Remember FCC encourages the Read-Search-Ask method.
If you are unsure of anything, ask further questions about it sure but do some background reading also.

If you are at University you don’t get all your knowledge from lectures. You read more about a subject in your own time (at least that’s what I did).