Skip to main content

Command Palette

Search for a command to run...

JavaScript Modules: Import and Export Explained

Updated
6 min read
JavaScript Modules: Import and Export Explained

When you first start learning JavaScript, it is completely normal to write all of your code inside a single file named app.js or script.js.

This works perfectly fine when you are writing a 50-line script to toggle a dark mode button. But what happens when you start building a massive web application like an e-commerce store? Your app.js file quickly grows to 1,000 lines, then 5,000 lines, and suddenly, you are scrolling endlessly just to find one tiny function that calculates the shopping cart total.

This is famously known as Spaghetti Code, everything is tangled together.

To solve this, modern JavaScript (ES6) introduced Modules. Let's explore why modules are the secret to writing clean, maintainable code, and how to use import and export to organize your projects like a pro.

Why modules are needed? (The Problem)

Imagine trying to build a Lego castle, but instead of having different bags for the walls, the characters, and the vehicles, all 5,000 pieces are dumped into one giant pile on the floor. Finding the exact piece you need is a nightmare. Before modules, JavaScript developers faced three major problems:

  1. Unmaintainable Files: Massive files are impossible to read, debug, or navigate.

  2. Global Variable Collisions: If you wrote let total = 0 at the top of a giant file, no other part of your app could use the variable name total without breaking everything.

  3. Hard to Collaborate: If five developers try to edit the same app.js file at the same time, Git merge conflicts will ruin your day. The Solution: We break our code into smaller, independent files called Modules. Each file has one specific job (e.g., one file for user authentication, one for math calculations).

Exporting functions or values**: Sharing Your Code**

By default, everything you write inside a JavaScript module is strictly private. If you create a variable or a function in mathUtils.js, your app.js file cannot see it.

To make a function available to other files, you must explicitly Export it. There are two ways to do this: Named Exports and Default Exports.

A. Named Exports (For sharing multiple things)

If a file contains several helper functions, you use Named Exports. You simply put the word export in front of the variable or function.

// file: mathUtils.js
export const pi = 3.14159;

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

B. Default Exports (For sharing one main thing)

If a file's entire purpose is to do just one main thing (like a React Component or a single User class), you use a Default Export. A file can only have one default export.

// file: User.js
export default class User {
  constructor(name) {
    this.name = name;
  }
  
  login() {
    console.log(`${this.name} logged in!`);
  }
}

Importing modules : Bringing Code Together

Now that we have exported our Lego pieces, how do we snap them together in our main app.js file? We use the import keyword!

A. Importing Named Exports

When you import named exports, you must use curly braces {}, and the names must match exactly what was exported.

// file: app.js

// Notice the curly braces and exact names!
import { add, pi } from './mathUtils.js';

console.log(pi); // Outputs: 3.14159
console.log(add(5, 10)); // Outputs: 15

B. Importing Default Exports

When you import a default export, you do not use curly braces. Because there is only one default export per file, you can name it whatever you want when you import it!

// file: app.js

// No curly braces!
import User from './User.js';

const myUser = new User("Alia");
myUser.login(); // Outputs: "Alia logged in!"

Default vs named exports**: The Cheat Sheet**

Here is a quick summary to help you remember the rules:

Feature

Named Export

Default Export

Syntax

export const x = 1;

export default x;

Imports

Requires { }

NO { } needed

Naming

Import name MUST match

Import name can be anything

Limit

Unlimited per file

Only ONE per file

Benefits of modular code

Once you start using modules, you will never go back.

  • Maintainability: If the shopping cart breaks, you know exactly which file to open (cart.js). You don't have to scroll through thousands of lines of code.

  • Reusability: Wrote a great function to format dates? Export it! Now you can import that exact same file into your next three projects without rewriting the code.

  • Namespacing (No Collisions): Variables are scoped to their module. You can have a total variable in cart.js and a total variable in analytics.js, and they will never interfere with each other.

Practical Assignment: Building a Modular App

As part of my web development cohort evaluation, here is a conceptual demonstration of how I split my code into multiple files using both Named and Default exports.

File 1: stringUtils.js (Using Named Exports)

// We have multiple utility functions here
export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

export function makeLoud(str) {
  return str.toUpperCase() + "!!!";
}

File 2: Logger.js (Using Default Export)

// This file does ONE main thing
export default function logMessage(msg) {
  console.log(`[SYSTEM LOG]: ${msg}`);
}

File 3: main.js (Bringing it all together)

// Importing Named Exports (Notice the { })
import { capitalize, makeLoud } from './stringUtils.js';

// Importing Default Export (No { })
import logMessage from './Logger.js';

// --- Using our imported modules ---
const rawInput = "hello world";

const neatString = capitalize(rawInput);
logMessage(neatString); // Output: [SYSTEM LOG]: Hello world

const angryString = makeLoud(rawInput);
logMessage(angryString);   // Output: [SYSTEM LOG]: HELLO WORLD!!!

E:\Hitesh_Web_Dev_2026\blog_folder\JavaScript-blogs\22.JS-JavaScript Modules Import and Export Explained>node main.js
[SYSTEM LOG]: Hello world
[SYSTEM LOG]: HELLO WORLD!!!

Conclusion

JavaScript Modules (import and export) are the foundation of modern web architecture. Whether you are building Vanilla JS applications or working with powerful frameworks like React, Vue, or Angular, modules are what allow us to build massive, scalable applications out of small, simple, and beautifully organized Lego blocks.

Quick Summary

  • Modules = separate files

  • export = code share karna

  • import = code use karna

  • Named vs Default difference important

  • Clean & scalable code