JavaScript Module Basics 📚

JavaScript modules are fundamental for organizing code in modern web development. They allow you to split your code into reusable components and manage dependencies effectively. Here's a quick guide to get started:

What is a Module? 💡

A module is a self-contained unit of code that can be imported and used in other programs. It typically contains functions, variables, or classes that are exported for external use.

Module System 🧩

JavaScript uses a module system to handle imports and exports. The two main systems are:

  • CommonJS (used in Node.js)
  • ES6 Modules (used in modern browsers and Node.js v14+)

File Structure 📁

A typical module file might look like this:

// math.js
export function add(a, b) {
  return a + b;
}

export const PI = 3.14159;

Using Modules 🔄

To use a module, you can import its contents:

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

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

Best Practices ✅

  • Keep modules focused on a single responsibility
  • Use descriptive names for modules and exports
  • Avoid exporting unnecessary variables or functions

For more information about ES6 modules, check out our ES6 Modules guide. Want to learn about asynchronous operations? Explore Async/Await next!

module_basics