More JavaScript 101: Module Patterns
Dan-Vy Le
Posted on January 21, 2020
Continuing from my previous blog post, more javascript 101 questions!:
Module Patterns
Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized. The Module Pattern is great for services and testing/TDD.
The Module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering. This helps reduce the chance of having conflicting function names with other functions in your code.
Before ES6, modules looked similar to this, stating private variables first, return
ing variables to make them public and then immediately invoking them at the end with ()
at the bottom.
(function() {
// declare private variables and/or functions
return {
//declare public variables and/or functions
}
}
})();
After ES6, modules have been created to be accessible in classes in other files. private properties are established in the constructor and public methods are still below being return
ed. The class is created and you can export the class. It can then be imported in any other files for use. FreeCodeCamp has a great example of this:
//lib/module.js file
class ShoppingDataType {
constructor() {
//private Properties
this.shoppingList = ['bananas', 'oranges', 'apples']
}
// public methods
getShoppingList() {
return this.shoppingList.join(", ")
}
addItem(item) {
this.shoppingList.push(item)
}
}
export default ShoppingDataType;
// main.js file
import ShoppingDataType from 'lib/module';
var shopping = new ShoppingDataType;
console.log(shopping.getShoppingList());
There are many schools of thought on how to design your code in javascript and module patterns is just one. Click here for more information on other design patterns
That's all for today, please leave any comments/questions/corrections in the comments. Thanks!
Sources:
Huge huge thanks to github user: yangshun for aggregating the most popular JS, CSS and HTML questions and giving us his answers to it. My weekly blog posts are to go over several questions at a time to reinforce my knowledge of fundamental javascript as I grow my expertise in it. Many of my blog will be paraphrasing if not direct quote from his github. Find his tech interview handbook here and please support him!
And an additional thank you to Flatiron alum: Marissa O. who is a badass developer at Forbes magazine for directing me to his blog!
Other sources:
https://coryrylan.com/blog/javascript-module-pattern-basics
https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
Posted on January 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.