Home »
JavaScript
Modules in JavaScript
JavaScript Modules: In this tutorial, we are going to learn about the modules in JavaScript with examples.
Submitted by Siddhant Verma, on November 22, 2019
JavaScript Modules
One of the key features of programming fundamentals is breaking down your code into fragments. These fragments depending on its functionality have been coined various terms like functions, components, modules, etc. Today we'll understand what modules are, why they are needed and how to create modules in JavaScript?
How to create modules in JavaScript?
Imagine you're working on an application that seamlessly gets bigger and bigger in terms of lines of code. Of course, the first thing you did was create that hefty code a bit modular by breaking it down in functions. Good, but now you have a lot of functions. Wouldn't it make sense to organize your code into different scripts? These scripts are called "modules". You're dividing your script into numerous other scripts to keep the code more modular and organized. Modularity is a key concept for object-oriented programming too and it sort of follows the same pattern.
Advantages of Modules in JavaScript
The three major advantages of Modules in JavaScript are maintainability which simply distributed codebase, Namespacing which implies that unrelated code do not share global variables and reusability, which is quite self-explanatory. That piece of code can be reused for other projects too.
Writing modular JS is using closures
The first way of writing modular JS is using closures.
Closures help us create anonymous functions and hide variables from parent scope. We can use local variables inside our function without collision with the same variables (having same name) outside because of their scope.
Example
<script>
(function() {
// We keep these variables private
// inside this closure scope
var HP = [10, 40, 87, 66, 45, 90];
var defeating = function() {
var defeated = HP.filter(function(item) {
return item < 50;
});
return 'You were defeated ' + defeated.length + ' times.';
}
console.log(defeating());
}());
</script>
Output
You were defeated 3 times.
Create modules using an object like interface
Another approach is to create modules using an object like interface. Let's modify the above code only,
Example
const pokebattle=(function () {
var HP = [10, 40, 87, 66, 45, 90];
return{
defeating: function(){
var defeated = HP.filter(function(item) {
return item < 50;});
return 'You were defeated ' + defeated.length + ' times.';
}
}
}());
console.log(pokebattle.defeating());
</script>
Output
You were defeated 3 times.
Using CommonJS
Using CommonJS, we can have each script as a module and use the keywords module.exports to export a module and require to import them.
Example
function Pokemon() {
this.greet = function() {
return 'Hey this is squirtle';
}
this.catchPhrase = function() {
return 'Squirtle Squirtle';
}
}
module.exports = Pokemon;
And when someone wants to use our pokemon module inside their local js file they can simply do,
var pokeModule = require('Pokemon');
var pokeInstance = new Pokemon();
pokeInstance.greet();
pokeInstance.catchphrase();
Output
Hey this is squirtle
Squirtle Squirtle
Most web frameworks make use of modules extensively. If you have used Node.Js ever you must have noticed very frequently you're importing a module from the core Node.js and then using it. For ex using the fs module for writing and reading from a file,
const fs=require('fs');
The above syntax states that you're importing a node module called fs inside the fs variable so now you can use it anywhere in that file.
Or if you use express to create a server in Node.js,
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Listening on port 3000...');
});
If you've worked with frontend frameworks like Angular, Vue or React; the modular code pattern is the crux behind their component based architecture. In fact, the first few lines you write every time you're coding in React are,
Import React, {Component} from 'React';
Thus modular patterns are very widely used today and almost everywhere. Massive libraries that utilise and make packages for JS are also modules. We have packages for bundling these modules like Webpack.
JavaScript Tutorial »