Hello and welcome back to the series of learning JavaScript. So far, we’ve been talking about asynchronous programming–building callbacks, Promises, and Async/Await. In this tutorial, we will begin to explore modular programming of JavaScript, and talk a bit about how we could use ECMAScript 6 modules for maintaining huge codebases organized and easier to deal with.
Why Modularization?
As of the front-end application grows, code organization and maintainability becomes of more significant importance. Modularization eases an otherwise monolithic codebase by breaking up into rather independent small blocks. Every module performs a specific function, its advantages underlined as given below:
Ease of Maintenance: Since each module is independent, it is easier to comprehend and change.
Reusability: Common functionalities can be broken into independent modules for easy reuse across other projects.
Dependency Management: Due to clear modularization, it is pretty easy to manage the dependency between different parts.
Basics of ES6 Modules
ES6 came up with a native module system. It provided us the ability to import and export modules using import and export statements.
Exporting Modules
You could use the export statement to export functions, variables, classes etc., from a file so that it’s available to import in some other file.
// file: mathUtils.js
export function add(x, y) {
return x + y;
}
export function subtract(x, y) {
return x - y;
}
Importing Modules
Using the import statement, you can import modules exported by other files.
// file: app.js
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
Default Export and Import
You can set a module as a default export, which is especially useful when each module has one main export.
// file: StringUtils.js
export default function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
Importing a default export:
// file: app.js
import capitalize from './StringUtils.js';
console.log(capitalize("hello")); // Output: Hello
Practical Exercise: Creating a Modularized Project
Let’s create a simple project that contains mathematical tools and string processing tools, each in its own module.
Create Modules: Create mathUtils.js and StringUtils.js as shown in examples.
Use Modules: In the main application file app.js import those tools and use those
Not only this makes the code more clear and organized but also the maintenance and expansion of it is lot easier.
Summary
Therefore, modularization is one of the key concepts for the development of modern JavaScript. Due to the capabilities of modules in ES6, we can now write cleaner, more structured, and much more manageable applications. Continue to learn all these techniques and try to apply them to real tasks. In the next lesson, we are going to discuss. See you again!