The Module Pattern in Javascript (aka Immediately-Invoked Function Expression aka IIFE)

Share this video with your friends

Send Tweet

Javascript modules are a design pattern that allow you to encapsulate your code into smaller self managing pieces. They help you separate your code, protect your variables, and provide an easy way to expose only the parts of your component that you want to be exposed.

James Pessato
~ 9 years ago

How do you approach the scenario where a module is dependant on another module or library? Does this pattern still work with that scenario?

Jeremy Robertsoninstructor
~ 9 years ago

@James: This pattern works great for that scenario. You actually have two ways to receive dependencies.

If you have a static dependency: //Have your module receive the dependency as a parameter var calculator = (function (myDependencyAsAParameter){

}(myDependency);

If you have a dynamic dependency that may change at run time you can pass it in when you invoke the module just like how the example is doing with the onUpdateResult function.