How to Use Import and Export in JavaScript: Simple Guide
In JavaScript, use
export to share variables, functions, or classes from one file, and import to bring them into another file. This helps organize code by splitting it into reusable modules.Syntax
Export lets you share code from a file. You can export named items or a default item.
export const name = value;exports a named variable.export default function() {}exports a default item.
Import brings exported items into another file.
import { name } from './file.js';imports a named export.import anyName from './file.js';imports the default export.
javascript
/* Exporting named and default items in module.js */ export const greeting = 'Hello'; export function sayHi() { return greeting + ', world!'; } const secret = 42; export default secret;
Example
This example shows how to export a function and a variable from one file and import them in another file to use them.
javascript
// file: mathUtils.js export function add(a, b) { return a + b; } export const pi = 3.14159; // file: main.js import { add, pi } from './mathUtils.js'; console.log('Add 2 + 3 =', add(2, 3)); console.log('Value of pi:', pi);
Output
Add 2 + 3 = 5
Value of pi: 3.14159
Common Pitfalls
Common mistakes include:
- Forgetting to use
{ }when importing named exports. - Trying to import a default export with curly braces.
- Using relative paths incorrectly (always include
.jsextension in many environments). - Mixing CommonJS
requirewith ES modulesimport/export.
javascript
// Wrong: importing named export without braces // import add from './mathUtils.js'; // ❌ // Correct: import { add } from './mathUtils.js'; // ✅ // Wrong: importing default export with braces // import { secret } from './module.js'; // ❌ // Correct: import secret from './module.js'; // ✅
Quick Reference
| Usage | Syntax Example |
|---|---|
| Export named variable | export const name = value; |
| Export named function | export function func() {} |
| Export default item | export default expression; |
| Import named exports | import { name } from './file.js'; |
| Import default export | import anyName from './file.js'; |
Key Takeaways
Use
export to share code and import to use it in other files.Named exports require curly braces when importing; default exports do not.
Always use correct relative paths and include file extensions if needed.
Do not mix CommonJS
require with ES module import/export syntax.Organizing code with modules improves readability and reuse.