Skip to main content

Command Palette

Search for a command to run...

JavaScript Modules: Import and Export Explained

Published
3 min read
JavaScript Modules: Import and Export Explained

When we start writing small programs, everything usually goes inside a single file.

That works fine in the beginning.

But as the project grows, we start adding more functions, more logic and more features.

Slowly, one file becomes very big and difficult to manage.

function add(a, b) { return a + b }
function multiply(a, b) { return a * b }
function divide(a, b) { return a / b }
// many more functions...

Now everything is mixed in one place.

It becomes harder to:

  • find code

  • reuse code

  • maintain code

This is where modules come in.


Why Modules Are Needed

Modules help us split code into multiple files.

Each file can handle a specific responsibility.

For example:

Instead of writing everything in one file, we organize code into smaller pieces.

This makes the code easier to read and manage.


Exporting Code

To use code from one file in another, we need to export it.

Example: math.js

export function add(a, b) {
  return a + b
}

export function multiply(a, b) {
  return a * b
}

Here we are exporting two functions.

Now these functions can be used in other files.


Importing Code

To use exported functions, we import them.

Example: app.js

import { add, multiply } from "./math.js"

console.log(add(2, 3))
console.log(multiply(4, 5))

Now app.js can use functions defined in math.js.


Default vs Named Exports

There are two ways to export things.

Named Export

This is what we saw earlier.

export function add(a, b) {
  return a + b
}

Importing:

import { add } from "./math.js"

We must use the same name while importing.


Default Export

A file can also have one default export.

export default function subtract(a, b) {
  return a - b
}

Importing:

import subtract from "./math.js"

Here we can use any name while importing.


Module Flow

Data flows from one file to another using import/export.


Benefits of Modular Code

Using modules improves code in many ways.

Better organization Code is split into smaller files.

Reusability Functions can be reused in different files.

Maintainability Changes in one module don’t affect everything.

Readability Each file has a clear purpose.


Small Example

math.js

export function square(num) {
  return num * num
}

app.js

import { square } from "./math.js"

console.log(square(5))

Output

25

As applications grow, keeping everything in one file becomes difficult.

Modules help us break code into smaller, manageable pieces.

Using export and import, we can share code between files and build better structured applications.