Modules and Namespaces in JavaScript

modules and namespaces in javascript

For most of us, modules and namespaces in JavaScript were kinds of tricky. We import a bundle and it does the magic. How and why is abstracted away. And before modules, ideas of IIFE, closure, etc made this arena unreachable for junior JavaScript developers.

Besides the easiness it brings, modularity has a number of advantages. However, to understand the benefits well we must first start with the problem.

First, let’s understand the problem that necessitates modularity?

We write a piece of code to fix a specific problem. For example, just last week we wrote a utility date function to move date by n number of dates. We might have a number of similar date functions. Since date manipulation is a common task, we will definitely need these utility functions in our projects.

So what do we do?

One approach is to copy that file in every project we work on. The problem with this approach is we will definitely need to make changes to our file. That means, we have to do this change everywhere it is used.

A better approach is the modular approach. In which case we prepare the file as a module. Then we can import and use it in our projects.

ES6 Makes Modules and Namespaces in JavaScript vary easy

The main idea regarding modules is to make a piece of code reusable.

class User {
  constructor(name, bday, sex) {
    this.name = name;
    this.bday = bday;
    this.sex = sex;
  }
}
function calculateAge(user) {
  today = new Date();
  const age = today.getFullYear() - user.bday.getFullYear();
  return age;
}
function displayUser(user) {
  console.log(`User is ${user.name} and is ${calculateAge(user)}`)
}

So, in the above piece of code, we have a User.js class with a class to instantiate a User object. Additionally, it has some important functions like calculateAge and displayUse. We don’t want to rewrite these functions. Instead, what we want is to import this piece of code into our other piece of code, every time we want to work with user.

And ES6 gives us a way to do that. For instance, we can use the import and export statements that are made supported in major browsers.

Exporting a JavaScript functionality into another script

Alright, so we have a pretty nice code and we don’t want to rewrite it. Rightly so.

Before we can reuse them, we have to make them available. And for that, we use the exports statement. In ES6, we can export variables, functions, and classes. Let’s see this in practice using the above code.

export default class User {
  constructor(name, bday, sex) {
    this.name = name;
    this.bday = bday;
    this.sex = sex;
  }
}
export function calculateAge(user) {
  today = new Date();
  const age = today.getFullYear() - user.bday.getFullYear();
  return age;
}
export function displayUser(user) {
  console.log(`User is ${user.name} and is ${calculateAge(user)}`)
}

As you can see, the easiest way is to just put export keywords in front of the classes and functions. Also, notice that the class has default right after export. And that is to indicate the default export. It is important to remember that we can only export one thing as default.

We can accomplish exactly the same thing with an alternative approach.

class User {
  constructor(name, bday, sex) {
    this.name = name;
    this.bday = bday;
    this.sex = sex;
  }
}
function calculateAge(user) {
  today = new Date();
  const age = today.getFullYear() - user.bday.getFullYear();
  return age;
}
function displayUser(user) {
  console.log(`User is ${user.name} and is ${calculateAge(user)}`);
}
export default User;
export { calculateAge, displayUser }

Importing a JavaScript functionality into our script file

Once we have our export statements readied, we are in a good position to go ahead and use them. And to use our module we use the import statement like this.

import User, {displayUser} from './User.js';
const user = new User("Alex", "18/07/1999");
user.displayUser(user);

Your subscription could not be saved. Please try again.
Your subscription has been successful.

Learn Modern JS, CSS, & PHP

Subscribe to learn modern PHP in the most simple way.