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.


💡 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.
| Type | Syntax | Example |
|---|---|---|
| Named Export | export { name1, name2 }; | export const pi = 3.14; |
| Default Export | export 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.
| Type | Syntax | Example |
|---|---|---|
| Named Import | import { name1, name2 } from 'module'; | import { pi } from './math.js'; |
| Default Import | import 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
// 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
exportto share code from a module. - Use
importto bring code into another module. - Named exports allow exporting multiple bindings.
- Default exports allow exporting a single main value.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which keyword is used to expose variables or functions from a module?
Question 2 of 2
How do you import a default export from a module?
Loading results...