Javascript Patterns: Modular Pattern

Javascript Patterns: Modular Pattern

A guide to understanding the Modular pattern in Javascript with its pros and cons and real-world use cases.

Let's start with a basic overview of Modular patterns in javascript first. In the modular pattern, we have different files containing some kind of logic, functions, or variables which can be exported from those files and imported into where we have to use them.

Let's look at an example: We have a module called Math.js from where we export two functions.

// Math.js
export function multiplyByTwo(number) {
  return number * 2;
}

export function subtractByTwo(number) {
  return number - 2;
}

We have an index.js file in which we import our module functions from the Math.js

// index.js
import { multiplyByTwo, subtractByTwo } from './math.js';

This is the most basic form of modular pattern where we can create multiple modules in files and then import them to be used anywhere.

We can also encapsulate or restrict some of our module's logic for example in the below example we have a secret value that we don't want to share with other modules or files so we can make the variable secret by simply not exporting it.

const secretValue = "some value"

export someFunction(){
console.log('This is a function');
}

Now importing the secret value in our index.js file would result in an error. Since we did not export it will only remain in that module encapsulated.

ES2015 approach :

Alternatively, in ES2015 we can use modular patterns as well, and the example below shows how it worked.

In the index.html file, we import our module math.js with the script syntax.

// index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="math.js"></script>
    </head>
    <body class="card" id="content">
<div></div>
    </body>
</html>

Then in our index.js file, we can use the math.js module functions:

// index.js
console.log('This is multiplied value of number', multiplyByTwo(2))

The problem with this approach is that our script imports all the module functions and even those which are not exported from the math.js in order to solve that we can add a type="module" with our script.

// index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="math.js" type="module"></script>
    </head>
    <body class="card" id="content">
<div></div>
    </body>
</html>

Tradeoffs.

Encapsulation:

The values within that module are scoped to that specific module. Values that aren't explicitly exported are not available outside of the module.

Reusability:

We can reuse modules in all applications.

So, guys, I hoped you would appreciate my 2 cents on this javascript pattern and let me know in the comments section what other benefits you see with this approach.

Sign in off.