- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Modules
We will explore JavaScript modules in this tutorial. Along with this, we will discover how to utilise it to encapsulate code and encourage code reuse.
JavaScript modules are independent chunks of code that may be imported and exported as necessary and help to encapsulate (enclose) code functionality. We can divide our codebase into independent files or modules, each of which can represent a different programming component, by using modules. The project's code is better ordered, naming conflicts are reduced, tree shaking is enhanced, and code reuse is made simpler using this modular approach.
Let’s understand the above concept with the help of some examples.
Example 1: Using Named Exports
In this explanation, we'll use named exports to export a javascript module and use it using the ES6 module syntax in our index.html file.
Filename: module.js
// module.js export function sayHello() { console.log("Hello!"); } export const message = "Welcome to the module!";
Filename: main.js
import { sayHello, message } from "./module.js"; sayHello(); // Output: Hello! console.log(message); // Output: Welcome to the module!
Filename: index.html
<html> <head> <title>JavaScript modules</title> <script type="module" src="module.js"></script> <script type="module" src="main.js"></script> </head> <body> <h3>JavaScript modules</h3> </body> </html>
Output
Example 2
In this example, we will use default exports to export a javascript module and use it in our index.html file by using the ES6 module syntax.
Filename: module.js
// module.js export default function greet() { console.log('Greetings!'); }
Filename: main.js
// main.js import greet from './module.js'; greet(); // Output: Greetings!
Filename: index.html
<html> <head> <title>JavaScript modules</title> <script type="module" src="module.js"></script> <script type="module" src="main.js"></script> </head> <body> <h3>JavaScript modules</h3> </body> </html>
Output
Conclusion
JavaScript modules are a great feature in javascript that allows us to organize and structure our code more efficiently. They allow us to encapsulate our code functionality, promote code reuse, and manage dependencies effectively. They also enhance code maintainability, scalability, and collaboration among team members. We learned the concept of modules in javascript and saw some examples explaining the same.