Skip to main content

Command Palette

Search for a command to run...

JavaScript Modules: Import and Export Explained

Updated
4 min read
JavaScript Modules: Import and Export Explained

Does modules are from the beginning of the JavaScript?

NO.

Before Modules, all code shared a single global space, which lead to major headches of Global Namespace pollution, The "Script order" Nightmare and the Lack of Encapsulation.

Why modules are needed

To write code in a single file is major headache, and debugging is even tougher if the same name of two utils function, which can lead to "naming collisions" where one script accidently overwrites another.

Modules solve this problem by splitting the large codebase into smaller, manageable pieces. They are essential for modern development as they solve critical issues related to scaling and code organisation.

Modules are primarily needed for:

  • Preventing Global Scope Pollution: Without modules, all variables and functions live in a single global space, which can lead to "naming collisions" where one script accidentally overwrites another. Modules have their own private scope, exposing only what is explicitly exported.

  • Encapsulation and Security: You can hide internal implementation details and only expose a public interface. This prevents outside code from unintentionally modifying sensitive data.

  • Explicit Dependency Management: Modules use import and export to clearly define relationships. This is far more reliable than manually ensuring multiple <script> tags are loaded in a specific, perfect order.

  • Code Reusability: You can write a utility function or class once in a module and easily reuse it across different parts of an application or even in entirely different projects.

  • Better Performance:

    • Lazy Loading: Modules can be loaded only when needed (dynamic imports), which reduces initial page load times.

    • Tree Shaking: Modern build tools can analyze module imports to remove unused code, resulting in smaller file sizes.

  • Singleton Behaviour: Modules are executed only once, even if imported multiple times. This makes them ideal for managing shared services or global-like state without polluting the actual global scope.

Exporting functions and Importing function

You have two main ways to share code. The choice usually depends on whether a file does one main thing or provides a "toolbox" of utilities.

Named Exports

Great for utility libraries where you want to export multiple functions from one file. You must use the exact name when importing.

// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// main.js
import { add, subtract } from './mathUtils.js';

Default Exports

Used when a module has one primary purpose (like a Class or a specific Component). You can name it whatever you want when importing.

// Logger.js
export default class Logger { ... }

// main.js
import MyLogger from './Logger.js'; 

Singleton Behavior (Shared State)

As mentioned, modules are executed only once. This is a "hidden" superpower. If three different files import the same AuthService.js, they all get the exact same instance of that service. This makes modules a perfect place to store:

  • User authentication tokens.

  • Theme settings (Light/Dark mode).

  • Database connections.

Benefits of modular code

Beyond solving technical bugs, modules transform how teams work:

  • Parallel Development: One developer can work on the Header module while another works on Footer without ever touching the same file.

  • Easier Testing: You can test a single function in a module in isolation without needing to load the entire website.

  • Predictability: When you look at the top of a file and see import { login } from './api.js', you know exactly where that function comes from. No more searching through 20 script tags to find a definition.

Conclusion

JavaScript modules have evolved from an optional pattern into the standard foundation for all modern web development. By moving away from "spaghetti" code and global variables, they provide a structured way to build everything from simple scripts to massive, enterprise-level applications.

Final Thoughts

Mastering modules isn't just about learning import and export syntax—it’s about adopting a modular mindset. As you continue your journey, keep these takeaways in mind:

  • Scalability & Structure: Modules allow you to break complex problems into small, single-purpose files that are easier to understand, test, and debug.

  • Performance First: Modern tools leverage the static nature of modules for Tree Shaking, which can reduce initial bundle sizes by up to 30% by stripping away unused code.

  • Future-Proofing: While systems like CommonJS still exist in legacy environments, ES Modules (ESM) are the native standard supported across all major browsers and Node.js.

Whether you're working solo or in a large team, leveraging modules ensures your code remains clean, secure, and ready for whatever the JavaScript ecosystem brings next.

Happy coding! 💕