JavaScript Modules

Understanding and Implementing Modular JavaScript

JavaScript Modules

JavaScript modules are a way to organize and structure code by splitting it into separate files. They help in creating more maintainable and reusable code.

Export

Use the export keyword to make functions, objects, or primitive values accessible to other modules.

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

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

export const PI = 3.14159;

Import

Use the import keyword to bring functions, objects, or values from other modules into the current module.

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

console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6
console.log(PI); // Output: 3.14159

Default Export/Import

You can have one default export per module, which can be imported without using curly braces.

// person.js
export default class Person {
constructor(name) {
this.name = name;
}
}

// main.js
import Person from './person.js';

const person = new Person('John');
console.log(person.name); // Output: John

Dynamic Import

Dynamic imports allow you to load modules on demand using the import() function.

async function loadModule() {
const module = await import('./dynamicModule.js');
module.doSomething();
}

loadModule();

Benefits of Modules

  • Better code organization and maintainability
  • Encapsulation and privacy
  • Reusability across different projects
  • Easier dependency management
  • Improved performance through lazy loading

Using modules in JavaScript is a powerful way to structure your code, making it more organized, maintainable, and scalable.