Skip to main content

Command Palette

Search for a command to run...

JavaScript Modules: Import and Export Explained

Published
3 min read
JavaScript Modules: Import and Export Explained

Why We Need Modules

In the early days of the web, scripts were loaded one after another. This led to several "code organization nightmares":

  • Global Namespace Pollution: Variables from one file would accidentally overwrite variables in another.

  • Dependency Confusion: It was hard to tell which file relied on which other file.

  • Maintenance Scars: Changing a function in one file could break a hidden dependency five files away.

Modules turn your codebase from a tangled ball of yarn into a set of organized LEGO bricks.


The Import/Export Flow

Think of a module as a high-security building. Everything inside is private by default.

  1. Export: You "unlock" specific doors to let certain functions or values out.

  2. Import: Another file "reaches in" through those doors to bring those values into its own scope.


1. Exporting: Sharing Your Code

There are two ways to share code from a module: Named Exports and Default Exports.

Named Exports

Use these when you want to export multiple things from a single file. You must use the exact name when importing them later.

JavaScript

// math-logic.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export const PI = 3.14;

Default Exports

Use this when a file has one "main" thing to offer (like a single class or a primary function). You can only have one default export per file.

JavaScript

// UserProfile.js
export default function UserProfile(name) {
  this.name = name;
}

2. Importing: Using Shared Code

Once you've exported something, you bring it into another file using the import keyword.

Importing Named Exports

You must wrap the names in curly braces { }.

JavaScript

import { add, PI } from './math-logic.js';

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

Importing Default Exports

You don't use curly braces, and you can actually rename the import whatever you like.

JavaScript

import User from './UserProfile.js'; 

const me = new User('Gemini');

Comparison: Default vs. Named Exports

Feature

Named Export

Default Export

Quantity

Multiple per file

Only one per file

Import Syntax

import { name } from '...'

import anyName from '...'

Naming

Must match the export name

Can be renamed freely

Best For

Utility libraries, math functions

Main components, classes


Benefits of Modular Code

  • Reusability: Write a "Date Formatter" once and use it in ten different projects.

  • Encapsulation: Keep complex logic hidden inside the module and only export the simple "buttons" the rest of the app needs to press.

  • Predictability: Because you explicitly list your imports at the top of the file, you can see exactly what a file depends on at a glance.