Member-only story
The Power of the Module Pattern in JavaScript
Embellish your app with the module pattern
In JavaScript, a widely used and powerful pattern is the Module Pattern. It can be incredibly simple to implement, but the fact that it enables developers to encapsulate their code makes it one of the most versatile patterns to build robust code. When you look inside the source code of JavaScript libraries, you’re most likely looking at an implementation of this pattern — and they’re most likely a singleton object, meaning that only one instance exists throughout the lifetime of an app.
It may be difficult for newcomers in JavaScript to understand the module pattern as there are several variations that exist. However, it’s worth all the time and trouble because you’ll be using this pattern very often to make your app more robust.
Modules
As you may have guessed, the module pattern lets you create modules. In the end, modules are basically just objects. But there are a couple of ways to create them.
The most basic way to create a module is to assign an object to a variable like so:
const myModule = {
drive() {
console.log('*drives*')
},
}
A simple image representation: