learn2kode.in

What Is Import and Export in JavaScript?

Import and export in JavaScript are part of ES6 modules, which allow you to share code between files. Instead of writing everything in one large script, you can split your code into reusable modules.
This makes your code cleaner, more organized, and easier to maintain.

Why Use Import and Export?

Using import and export helps developers:
Modern JavaScript applications rely heavily on module-based architecture.

Exporting Code in JavaScript

The export keyword is used to share code from a module.
export const appName = "Learn2Kode";

export function welcome() {
  return "Welcome to JavaScript Modules!";
}
You can export multiple values from a single file.

Importing Code in JavaScript

The import keyword allows you to use exported code in another file.
Named Export Example:
import { appName, welcome } from "./utils.js";

console.log(appName);
console.log(welcome());
The imported names must match the exported names exactly.

Default Export in JavaScript

A module can have only one default export.
export default function add(a, b) {
  return a + b;
}
Importing a default export:
import add from "./math.js";
console.log(add(2, 3));
Default exports are commonly used for main components or functions.

Default Export in JavaScript

A module can have one default export.
export default function add(a, b) {
  return a + b;
}
Importing a default export:
import add from "./math.js";
Default exports are flexible and commonly used.

Combining Named and Default Exports

You can use both export types in the same file.
export default function multiply(a, b) {
  return a * b;
}

export const version = "1.0";
import multiply, { version } from "./calc.js";
This pattern is widely used in real-world projects.

Import Everything from a Module

You can import all exports using *.
import * as utils from "./utils.js";

utils.welcome();
This is useful when a module has many exports.
Using Import and Export in HTML
To use modules in the browser, your script must include type=”module”.
<script type="module" src="main.js"></script>
Without this, import/export will not work in browsers.
Import / Export vs Regular Scripts
Common Mistakes with Import and Export
Always test modules using a local development server.

Real-World Use of Import and Export

Import and export are used in:
They are a core part of modern JavaScript development.

Final Thoughts

Learning JavaScript import and export is essential for writing scalable, professional code. Mastering this concept will help you build real-world applications with confidence.