D DevBrainBox

JavaScript Modules

JS

What are JavaScript Modules?

JavaScript modules are a way to split your code into separate files and pieces. Each file can export variables, functions, classes, etc. that can then be imported and used in other files.

Modules help in:

  • Keeping code organized and easy to maintain
  • Avoiding global namespace pollution
  • Reusing code across different files or projects

Example: ES6 Modules

Exporting

Suppose you have a file called math.js:

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

export const PI = 3.14;

// You can also have a default export
export default function multiply(a, b) {
 return a * b;
}

Importing

In another file called app.js, you can use these exports:

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

console.log(add(2, 3)); // 5
console.log(PI);        // 3.14
console.log(multiply(4, 5)); // 20
  • multiply is imported without curly braces because it was exported as default.
  • add and PI are imported using because they are named exports.

Why use modules?

  • To keep code modular, meaning easier to understand and test.
  • To avoid naming conflicts (everything is scoped to the module by default).
  • To load only the parts you need

On this page