Skip to main content

Command Palette

Search for a command to run...

JavaScript Modules: Import and Export Explained

A beginner-friendly guide to why modules matter and how import and export help organize JavaScript code

Updated
2 min read
JavaScript Modules: Import and Export Explained
P
IT graduate 2024. Learning software and web development in public. Writing about bugs, fixes, small projects, useful tools, and lessons from building things step by step.

Introduction

As JavaScript projects grow, one problem appears quickly:

keeping all the code in one file becomes messy

This is where modules become useful.


Why Modules Are Needed

If everything is in one file, then:

  • readability can decrease

  • maintainability can become difficult

  • reuse can feel awkward

Modules let us organize code into smaller, focused files.


Exporting Functions or Values

Export means:

something from this file can be used in another file

export const siteName = "Chaicode";
export function greet(name) {
  return `Hello ${name}`;
}

Importing Modules

Import means:

bringing an exported thing from another file into your current file

import { greet, siteName } from "./utils.js";

Named Exports

export const appName = "Chaicode";
export function add(a, b) {
  return a + b;
}
import { appName, add } from "./utils.js";

Default Export

export default function greet(name) {
  return `Hello ${name}`;
}
import greet from "./greet.js";

Default vs Named Exports

  • named export -> imported with the exact name

  • default export -> the main export of the file


Benefits of Modular Code

  • code becomes more organized

  • files stay smaller

  • reuse becomes easier

  • maintenance becomes better


A Small Example

math.js

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

main.js

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

console.log(add(2, 3));

Summary

  • modules are used to organize code into multiple files

  • export makes values or functions available to other files

  • import brings those values into the current file

  • default and named exports use different syntax

  • modular code is more maintainable and reusable


Final Thought

Modules move JavaScript from just working code toward structured code.

Once the import/export flow becomes clear, the idea of code organization starts to feel much more natural.


Continue Reading