Back to course

Introduction to Modules (Import and Export Basics)

JavaScript: The Complete '0 to Hero' Beginner Course

99. Introduction to Modules (ESM)

As applications grow, separating code into reusable files (modules) becomes essential for organization, maintenance, and avoiding global variable conflicts. ES Modules (ESM) are the modern, native solution.

1. Exporting

To make a function, variable, or class available in another file, you must export it.

Named Exports: Exporting multiple things from one file.

javascript // utils.js export const version = '1.0'; export function log(message) { console.log([LOG]: ${message}); }

Default Exports: Only one default export per module (often used for classes or main components).

javascript // User.js export default class User { /* ... */ }

2. Importing

Use the import keyword to bring those exports into a different file.

javascript // app.js import { version, log } from './utils.js'; import User from './User.js'; // Default export import doesn't use {} and can be renamed

log('Application starting...'); const newUser = new User();

Note: To run modules in the browser, your HTML <script> tag must include type="module".