Modules| Dataplexa

Modules

As JavaScript projects grow, keeping all code in a single file becomes difficult to manage.

Modules help you split code into smaller, reusable, and organized files.


What Is a Module?

A module is a JavaScript file that contains related code and exposes only what is needed.

Each module has its own scope, which helps avoid variable conflicts and keeps code clean.


Why Modules Matter

  • Better code organization
  • Improved maintainability
  • Reusability across files
  • Clear separation of responsibilities

Modules are essential for building scalable applications.


Exporting from a Module

To share code from a module, you use the export keyword.


// math.js
export function add(a, b) {
  return a + b;
}
  

This makes the function available to other files.


Importing into Another File

To use exported code, you import it using import.


// app.js
import { add } from "./math.js";

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

The path points to the module file.


Default Exports

A module can also export a single default value.


// logger.js
export default function log(message) {
  console.log(message);
}
  

Importing a default export looks slightly different.


import log from "./logger.js";

log("Hello Modules");
  

Named vs Default Exports

  • Named exports allow multiple exports per file
  • Default export allows one main export
  • You can mix both, but clarity matters

Modules in the Browser

To use modules in the browser, the script tag must include type="module".



  

This tells the browser to treat the file as a module.


Real-World Example

Large applications often organize code like this:

  • utils/
  • services/
  • components/
  • main app file

Modules keep responsibilities clear and isolated.


Common Beginner Mistakes

  • Forgetting type="module" in HTML
  • Using incorrect file paths
  • Mixing global scripts with modules

Always check module paths and browser support.


Thumb Rules

  • One module = one responsibility
  • Export only what is needed
  • Prefer named exports for clarity
  • Use modules for scalable code

What Comes Next?

Now that your code is organized into modules, the next step is applying modern JavaScript concepts together.

In the next lesson, we will build a modern JavaScript project.