0
0
JavascriptHow-ToBeginner · 4 min read

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 .js extension in many environments).
  • Mixing CommonJS require with ES modules import/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

UsageSyntax Example
Export named variableexport const name = value;
Export named functionexport function func() {}
Export default itemexport default expression;
Import named exportsimport { name } from './file.js';
Import default exportimport 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.