On this page

Modules in JavaScript

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A JavaScript module is a self-contained unit of code that encapsulates related functionality. They help to modularize your codebase, making it easier to manage and reuse code across different parts of your application. Modules can expose certain features or variables to be used by other modules while keeping the rest of their implementation private1.

Creating a Module​

A module in JavaScript is just a file of code. You can think of a module as a reusable and independent unit of code. As your application gets bigger, you can split your code up into multiple files, aka modules.


// myModule.js

export function myFunction() {

  return "Hello, World!";

}

In this example, myFunction is exported from the module, which means it can be imported into other modules.

Importing a Module​

Modules are imported from external files with the import statement.


// app.js

import { myFunction } from "./myModule.js";



console.log(myFunction()); // Outputs: 'Hello, World!'

In this example, myFunction is imported from myModule.js and then used in app.js.

Default Exports​

Each module can have one default export. Default exports are especially easy to import.


// myModule.js

export default function myFunction() {

  return "Hello, World!";

}



// app.js

import myFunction from "./myModule.js";



console.log(myFunction()); // Outputs: 'Hello, World!'

In this example, myFunction is the default export of myModule.js, so it can be imported without using curly braces.

Named Exports​

A module can have multiple named exports. You can import a specific named export using curly braces.


// myModule.js

export function function1() {

  return "Hello, World!";

}



export function function2() {

  return "Goodbye, World!";

}



// app.js

import { function1, function2 } from "./myModule.js";



console.log(function1()); // Outputs: 'Hello, World!'

console.log(function2()); // Outputs: 'Goodbye, World!'

In this example, function1 and function2 are named exports of myModule.js, so they can be imported individually.

Browser Compatibility​

Modern browsers have started to support module functionality natively. Use of native JavaScript modules is dependent on the import and export statements. These are supported in browsers as shown in the compatibility table.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Form Validation

Next

Asynchronous JavaScript