DEV Community

Cover image for JavaScript Modules Explained: Import, Export & Examples
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

JavaScript Modules Explained: Import, Export & Examples

JavaScript modules help organise your code by splitting it into separate files, making it easier to manage and reuse across projects. Modules enhance code maintainability, readability, and reusability.


How to Use JavaScript Modules

To work with modules, you need to importand exportfiles using the import and export statements. Additionally, modules require the type="module" attribute in the <script> tag.

Example: Importing a Module:

import greet from "./greet.js";
console.log(greet());

Enter fullscreen mode Exit fullscreen mode

Exporting Data from a Module

Modules allow exporting variables, functions, or classes from one file so they can be used in another. There are two types of exports in JavaScript: Named Exports and Default Exports.

1. Named Exports

Named exports allow you to export multiple values from a single module. You can export them either individually or all at once.

Example 1: In-line Named Exports
File: data.js

export const username = "JohnDoe";
export const age = 25;

Enter fullscreen mode Exit fullscreen mode

Example 2: Exporting All at Once
File: data.js

const username = "JohnDoe";
const age = 25;

export { username, age };

Enter fullscreen mode Exit fullscreen mode

To import named exports, use curly braces {}:


import { username, age } from "./data.js";
console.log(username, age);

Enter fullscreen mode Exit fullscreen mode

2. Default Exports

A module can have only one default export, which simplifies importing.

Example: Default Export
File: greet.js

const greet = () => "Hello, welcome to JavaScript Modules!";
export default greet;

Enter fullscreen mode Exit fullscreen mode

To import a default export, do not use curly braces {}:


import greet from "./greet.js";
console.log(greet());

Enter fullscreen mode Exit fullscreen mode

Why Use JavaScript Modules?

✔ Better Code Organization
✔ Improved Maintainability
✔ Code Reusability
✔ Avoid Global Namespace Pollution

By using modules, you can keep your JavaScript code structured and scalable. Start modularizing your code today!


Conclusion

JavaScript modules are a powerful feature that helps in writing clean, maintainable, and reusable code. By breaking code into smaller, independent files, you can improve project organization, avoid global namespace pollution, and enhance scalability. Whether you're working on a small project or a large application, using modules will make development more efficient and manageable.

Start implementing JavaScript modules in your projects today and experience the benefits of modular programming!

Top comments (0)