DEV Community

Sakshi Tambole
Sakshi Tambole

Posted on

JavaScript Modules: Import and Export Explained

JavaScript modules, using the import and export keywords, allow developers to break code into smaller, reusable files, promoting better organisation, maintainability, and encapsulation. This system, introduced in ES6, is the standard for modern JavaScript development.

🚧 Why JavaScript Modules Are Needed:

As JavaScript applications grow, writing all your code in a single file (or loosely connected files) quickly leads to serious problems. Modules were introduced to solve these issues and bring structure to your code base.

  1. Global scope pollution:
  • JavaScript applications without modules often suffer from global scope pollution, where variables and functions are defined in the global space and become accessible from anywhere in the code.

  • This creates a high risk of name collisions, especially in larger projects where multiple developers are working simultaneously.

πŸ’₯ Example

var user = "Alice";

var user = "Bob"; 

console.log(user); 
Enter fullscreen mode Exit fullscreen mode
  1. Hard-to-maintain code:
  • Another major issue is hard-to-maintain code.

  • When all logic is written in a single file or a few large files, the code base quickly becomes overwhelming.

  • These files can grow to thousands of lines, mixing different concerns such as business logic, UI handling, and utility functions in one place.

πŸ’₯ Example

function login() { /* ... */ }
function calculateTotal() { /* ... */ }
function renderUI() { /* ... */ }
function sendEmail() { /* ... */ }

Enter fullscreen mode Exit fullscreen mode

3.Lack of Re-usability:

  • The absence of modules also leads to a lack of re-usability.

  • Developers often end up copying and pasting the same functions across multiple files or projects instead of sharing them efficiently.

  • This duplication increases the size of the code base and creates maintenance challenges.

  • If a bug is found in a duplicated function, it must be fixed in every place where the code was copied, increasing the chances of inconsistencies and missed updates.

πŸ’₯ Example

function formatDate(date) {
  return date.toISOString();
}
(copied again)
function formatDate(date) {
  return date.toISOString();
}

Enter fullscreen mode Exit fullscreen mode
  1. Dependency Confusion:

  2. Finally, dependency confusion is a common problem in non-modular JavaScript.

  • In traditional setups, especially when using multiple script tags, there is no clear indication of which file depends on another.

  • Developers must manually manage the order in which scripts are loaded, and even a small mistake can break the application.

πŸ’₯ Example

<script src="math.js"></script>
<script src="app.js"></script>

Enter fullscreen mode Exit fullscreen mode

If app.js depends on math.js, the order matters.

πŸ“¦ Exporting Functions or Values:

In JavaScript modules, exporting functions or values allows you to make specific parts of a file available for use in other files. Instead of exposing everything globally, you explicitly choose what should be shared, which improves clarity and control.

  • The export keyword makes variables, functions, or classes available to other modules.

  • There are two types:

  • Named Exports

  • 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

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

Enter fullscreen mode Exit fullscreen mode

Example 2: Exporting All at Once

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);

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

Example: Default Export

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

πŸ“₯ Importing Modules:

What is importing?

Importing is the process of bringing functions, variables, classes, or other code from one module (file) into another module so they can be used there.

Import Named Exports

import { add, subtract } from './math.js';

console.log(add(2, 3));

Enter fullscreen mode Exit fullscreen mode

Import Default Export

import greet from './greet.js';

console.log(greet('Alice'));

Enter fullscreen mode Exit fullscreen mode

Import Everything

import * as math from './math.js';

console.log(math.add(2, 3));

Enter fullscreen mode Exit fullscreen mode

πŸ”„ Default vs Named Exports:

Default Exports:

A default export is the main thing a module provides.

  • Each file can have only ONE default export
  • When importing, you can choose any name
export default function greet() {}

Enter fullscreen mode Exit fullscreen mode
import greet from './greet.js';

Enter fullscreen mode Exit fullscreen mode

Named Exports:

Named exports let you export multiple values from a single file, each with its own name.

  • can have many named exports
  • It must import them using the exact same names

βš–οΈ Key Differences

Feature Named Export Default Export
Number allowed Multiple One per file
Import syntax { name } Any name
Use case Utilities, multiple items Main functionality

🧱 Benefits of Modular Code

  1. Maintainability
    Smaller files β†’ easier to understand.
    Changes are localized.

  2. Re-usability
    Share modules across projects.

  3. Testability
    Test individual modules in isolation.

  4. Team Collaboration
    Multiple developers can work on different modules.

  5. Scalability
    Code base grows without becoming chaotic.

πŸ“Š Diagram Ideas

1️⃣ File Dependency Diagram

app.js
 β”œβ”€β”€ math.js
 β”œβ”€β”€ greet.js
 └── utils.js

Enter fullscreen mode Exit fullscreen mode

2️⃣ Module Import/Export Flow

[ math.js ]
   |  export add, subtract
   ↓
[ app.js ]
   |  import { add }
   ↓
Use functions

Enter fullscreen mode Exit fullscreen mode

Top comments (0)