JAVASCRIPT

JavaScript Module: Syntax, Usage, and Examples

A JavaScript module is a reusable piece of code that you can import and export across files. Modules help keep your code organized, maintainable, and scalable by isolating functionality into separate files.

How to Use JavaScript Modules

To use JavaScript modules, you need to create separate files and explicitly export and import functions, objects, or variables. JavaScript modules follow the ES6 standard and use the export and import keywords.

Exporting a Module

You can export functions, variables, or objects using export. There are two ways to do this: named exports and default exports.

Named Exports

With named exports, you can export multiple values from a single module.


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

Default Export

A module can also have a default export, which allows importing it with any name.

// logger.js
export default function log(message) {
  console.log(`Log: ${message}`);
}

Importing a Module

You can import named exports using curly braces.

import { PI, add } from "./math.js";

console.log(PI); // 3.14159
console.log(add(5, 3)); // 8

For default exports, you don't need curly braces.

import log from "./logger.js";

log("This is a message"); // Log: This is a message

Using Modules in an HTML File

To use a JavaScript module inside an HTML file, add the type="module" attribute to the script tag.

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

When to Use JavaScript Modules

  1. Organizing Code – Modules help break down large scripts into smaller, reusable pieces.
  2. Avoiding Global Variables – Each module has its own scope, preventing conflicts between variables.
  3. Maintaining and Scaling Code – Large applications benefit from modularity, making it easier to debug and extend.

Examples of JavaScript Modules

Exporting and Importing Functions

You can split utility functions into separate files and import only what you need.

// utils.js
export function greet(name) {
  return `Hello, ${name}!`;
}

// main.js
import { greet } from "./utils.js";

console.log(greet("Alice")); // Hello, Alice!

Using Default Exports

If a module only contains one main function or object, use default exports.

// currency.js
export default function convert(amount, rate) {
  return amount * rate;
}

// main.js
import convert from "./currency.js";

console.log(convert(100, 1.1)); // 110

Importing Everything from a Module

You can import an entire module as an object to access multiple exports.

// math.js
export const PI = 3.14159;
export function multiply(a, b) {
  return a * b;
}

// main.js
import * as MathUtils from "./math.js";

console.log(MathUtils.PI); // 3.14159
console.log(MathUtils.multiply(2, 3)); // 6

Learn More About JavaScript Modules

Handling Import Errors

You might encounter an error like "Cannot use import statement outside a module" when trying to use import in a non-module script. To fix this, ensure that:

  • Your script tag in the HTML file includes type="module".
  • You're running the code in a proper environment (e.g., using a local server instead of opening the file directly).

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

JavaScript Module Exports

Modules allow multiple exports. You can mix named and default exports in a single file.

export const name = "Module Example";
export function sayHello() {
  return "Hello from a module!";
}

export default function mainFunction() {
  console.log("This is the default function.");
}

Importing Modules Dynamically

JavaScript supports dynamic imports using import(), allowing you to load modules only when needed.

async function loadModule() {
  const math = await import("./math.js");
  console.log(math.PI); // 3.14159
}

loadModule();

This is useful for lazy-loading and improving performance in large applications.

The Module Pattern

Before ES6 modules, developers used the module pattern with IIFEs (Immediately Invoked Function Expressions) to create private variables.

const Module = (function () {
  let privateVar = "I am private";

  return {
    publicMethod() {
      console.log(privateVar);
    },
  };
})();

Module.publicMethod(); // I am private

While ES6 modules are now the standard, this pattern can still be useful in some cases.

JavaScript Module Scope

Each module in JavaScript has its own scope, meaning variables declared inside a module are not accessible globally.

// module.js
const secret = "This stays inside the module";
export const publicVar = "This can be imported";

// main.js
import { publicVar } from "./module.js";
console.log(publicVar); // Works
console.log(secret); // Error: secret is not defined

Calling a JavaScript Module Function from HTML

You can call functions from a module in an HTML file by first importing the module into a script file.

// script.js
import { sayHello } from "./module.js";

document.getElementById("btn").addEventListener("click", () => {
  alert(sayHello());
});

<button id="btn">Click me</button>
<script type="module" src="script.js"></script>

Creating and Declaring JavaScript Modules

To create a module, define its functions and variables, then export them.

// myModule.js
export function square(x) {
  return x * x;
}
export function cube(x) {
  return x * x * x;
}

Then, import and use them in another file.

import { square, cube } from "./myModule.js";

console.log(square(3)); // 9
console.log(cube(3)); // 27

Common Mistakes and Best Practices

  • Always use type="module" in the script tag when working with modules.
  • Keep module files small and focused on a single purpose.
  • Use named exports for multiple utilities and default exports for single-use functions.
  • Use relative or absolute paths when importing modules (./module.js instead of module.js).
  • Be cautious when dynamically importing modules to prevent performance issues.

JavaScript Module Use Cases

  1. Reusing Utility Functions – Keep helper functions in separate modules.
  2. Organizing Large Applications – Break down a large project into smaller modules.
  3. Lazy Loading Code – Load modules only when they are needed to optimize performance.
  4. Encapsulating Private Variables – Prevent global scope pollution by isolating variables in modules.

Understanding JavaScript modules helps you write cleaner, more maintainable code. By structuring your projects with modules, you make your code easier to manage, debug, and scale.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH