Sitemap
Better Programming

Advice for programmers.

The Power of the Module Pattern in JavaScript

Embellish your app with the module pattern

6 min readNov 3, 2019

--

Press enter or click to view image in full size
Image
Photo by John Schnobrich on Unsplash

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:

Press enter or click to view image in full size
Image

Things start to become more interesting when we utilize some of JavaScript’s unique features to create a module, which we’ll cover next.

Immediately Invoked Function Expression

Arguably the most popular variation of the module pattern is the IIFE (Immediately Invoked Function Expression). These are essentially functions that invoke immediately and return an object (or an interface, in other words), which then becomes the module.

Inside these functions is code that can be private in such ways that it would only be accessible within that function’s scope unless the returned object provides methods that can access them somehow. This returned object is public and available to the outside world.

--

--

jsmanifest
jsmanifest

Written by jsmanifest

Team Lead Front End Developer for a TeleMedicine Company. Follow and Join Me on my Adventures. https://jsmanifest.com

Responses (2)