Modules in JavaScript

🔍 What are JavaScript Modules?

Modules in JavaScript are reusable chunks of code that encapsulate logic, variables, functions, or classes — allowing developers to maintain a clean, organized, and scalable codebase. 🌟 They help split large code files into smaller, manageable pieces.

Note

💡 Each module has its own scope, preventing variables from polluting the global namespace.

📤 Exporting from a Module

You can export variables, functions, or classes from a module so that they can be used in other files.

export.js

// Named export
export const name = "JavaScript";

// Multiple named exports
export function greet() {
  return "Hello from module!";
}

// Default export
export default function() {
  return "I am the default export!";
}

📥 Importing into a Module

import.js

// Importing named exports
import { name, greet } from './export.js';

console.log(name);      // "JavaScript"
console.log(greet());   // "Hello from module!"

// Importing default export
import defaultFn from './export.js';

console.log(defaultFn()); // "I am the default export!"

🧠 Types of Exports

  • Named Exports – You can export multiple values and import them by name.
  • Default Export – Only one per module; imported without curly braces.

🚀 Why Use Modules?

  • Improves code structure and maintainability 🧱
  • Reduces global variable collisions 🛡️
  • Facilitates code reuse and testing 🔁
  • Enables lazy loading and bundling for performance 🎯

🌐 Using Modules in HTML

To use ES Modules in the browser, specify type="module" in your script tag:

Code Snippet

<script type="module" src="main.js"></script>

Note

⚠️ Module scripts are deferred by default and run in strict mode.

🌍 Browser vs Node.js Modules

FeatureES ModulesCommonJS (Node.js)
Syntaximport/exportrequire/module.exports
EnvironmentBrowser & Node (ESM enabled)Node.js (default for .js)
SupportModern JS & bundlersLegacy Node modules

📁 File Extensions

  • .mjs – Used for ES modules in Node.js
  • .cjs – Used for CommonJS modules
  • .js – Can be used for either (needs context)

🔗 Related Concepts

>>“Modularity is the key to scalability in software.”