JavaScript Modules Explained With Import And Export

JavaScript modules allow you to organize code into separate files, making it easier to manage, reuse, and maintain. ES6 introduced export and import to handle modules.

This blog explains how to use modules with practical examples.


1. What Are JavaScript Modules?

A module is a file that contains code—variables, functions, or classes—that can be exported and used in other files. Modules help in keeping code clean and modular.


2. Exporting From a Module

Named Export

// file: mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

Default Export

// file: greeting.js
export default function greet(name) {
  console.log(`Hello, ${name}!`);
}

3. Importing Modules

Named Import

// file: app.js
import { add, subtract } from './mathUtils.js';

console.log(add(5, 3));      // 8
console.log(subtract(5, 3)); // 2

Default Import

// file: app.js
import greet from './greeting.js';

greet("Sagar"); // Hello, Sagar!

Import Everything

import * as math from './mathUtils.js';
console.log(math.add(10, 5)); // 15

4. Why Use Modules?

  • Organize code into smaller, manageable files
  • Reuse code across projects
  • Avoid polluting global namespace
  • Easier maintenance and testing

5. Using Modules in Browsers

Use the type="module" attribute in your HTML file:

<script type="module" src="app.js"></script>

Modules are loaded asynchronously and support modern ES6 syntax.


Conclusion

JavaScript modules are essential for modern web development. Using export and import allows you to write clean, modular, and reusable code, making your projects scalable and easier to maintain.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *