JavaScript Algorithms and Data Structures - Use an IIFE to Create a Module

I am looking at this lesson here:

It is not clear to me what the benefit of using an IIFE like this is. Would it not be more straight forward and efficient to assign the object directly to the motionModule variable as opposed to executing a function that just returns the same object?

What are the advantages that I am overlooking, as I am just seeing an intermediary extra step (the execution of the IIFE) compared to directly assigning the object.

Thanks in advance!

as it mentions in opening statement

An immediately invoked function expression (IIFE) is often used to group related functionality into a single object or module

and it also mentions

advantage of the module pattern is that all of the motion behaviors can be packaged into a single object that can then be used by other parts of your code

does that help, happy coding :slight_smile:

It scopes variables within it, allowing for values that can’t be accessed outside the module. If you just use an object you can just access everything in the object.

(as it is, JavaScript now supports actual modules, so the likelihood of you ever using this pattern is now close to nil, but using IIFEs was how it was done pre-2015)

Thanks for your reply! I don’t see that as an advantage for using IIFE’s specifically in this example because we could accomplish the same thing (that is the packaging of behaviors into a single object) without an IIFE - simply assign the object to the variable without the IIFE wrap.

I see, if it is that unlikely I will ever be using this pattern I guess I won’t spend too much time on it. Thanks!

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