SmartCodingTips

📦 JavaScript Modules

JavaScript modules let you split your code into separate files, making it easier to organize, maintain, and reuse. Modules export code from one file and import it into another.


🔹 Why Use Modules?

  • Organize code into smaller, reusable parts
  • Avoid global namespace pollution
  • Make maintenance easier
  • Encourage code reuse between projects

📤 Exporting from a Module

Use export to share variables, functions, or classes.

// math.js
export const PI = 3.14159;

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

// You can also export by default
export default function subtract(a, b) {
  return a - b;
}

📥 Importing a Module

Use import to bring in exported code.

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

console.log(add(5, 3));       // 8
console.log(subtract(10, 4)); // 6
console.log(PI);              // 3.14159
⚠️ When using modules in the browser, you must load them with:
<script type="module" src="main.js"></script>

📂 Module File Structure Example

project/
│── index.html
│── main.js
└── math.js

🛠 Named vs Default Exports

  • Named Exports — You can have many named exports per file
  • Default Export — Only one per file, imported without braces
// utils.js
export function greet(name) {
  return `Hello, ${name}`;
}

export default function farewell(name) {
  return `Goodbye, ${name}`;
}
// app.js
import farewell, { greet } from './utils.js';

console.log(greet("Alice"));     // Hello, Alice
console.log(farewell("Bob"));    // Goodbye, Bob

🌐 Modules in Node.js

Node.js uses CommonJS syntax by default:

// add.js
module.exports = function(a, b) {
  return a + b;
};

// main.js
const add = require('./add');
console.log(add(2, 3)); // 5

In newer Node.js versions, you can use ES modules by setting "type": "module" in package.json.


✅ Summary

  • Use modules to split your code
  • Named exports allow multiple exports per file
  • Default export is best for one main thing
  • In browsers, use type="module" in the script tag