Modules (import/export)

JavaScript modules allow you to split code into reusable pieces and share functionality between files. Modules use export to expose code and import to bring it in.

Illustration of Modules (import/export)
Illustration of Modules (import/export)
Illustration of modules_import_export
Illustration of modules_import_export

💡 Why use modules?

They help organize code, avoid polluting the global scope, and enable better maintainability and reuse.

Exporting

There are two main types of exports:

  • Named exports: Export multiple variables or functions by name.
  • Default export: Export a single value as the default export.
Export Syntax Comparison
TypeSyntaxExample
Named Exportexport { name1, name2 };export const pi = 3.14;
Default Exportexport default expression;export default function() {}

Importing

To use exported code, you import it in another file:

  • Named imports must use curly braces and match exported names.
  • Default imports use any name without braces.
Import Syntax Comparison
TypeSyntaxExample
Named Importimport { name1, name2 } from 'module';import { pi } from './math.js';
Default Importimport anyName from 'module';import greet from './greet.js';

💡 Mixing imports

You can import default and named exports together: import greet, { sayBye } from './greet.js';

Example: Export and Import

📌 Deep Dive: Named and Default Export/Import

JAVASCRIPT
// math.js
export const pi = 3.1415;
export function square(x) {
  return x * x;
}
export default function cube(x) {
  return x * x * x;
}
// app.js
import cube, { pi, square } from './math.js';

console.log(pi);          // 3.1415
console.log(square(4));   // 16
console.log(cube(3));     // 27

⚠️ Module Loading Note

Modules must be loaded with type="module" in browsers or via a bundler/Node.js environment that supports ES modules.

💡 Summary

  • Use export to share code from a module.
  • Use import to bring code into another module.
  • Named exports allow exporting multiple bindings.
  • Default exports allow exporting a single main value.