Skip to main content

Command Palette

Search for a command to run...

JavaScript Modules — Let's Keep It Simple

Updated
•3 min read•View as Markdown

Tell me one thing — in your house, do you have everything in one room? Kitchen, bathroom, bedroom, hall — all at one place?

Obviously not, right?

So then why would you want to keep all your code in one single file? That's exactly the problem modules solve.


So What Are Modules?

Modules are nothing but separate files for different types of code.

Just like your house has separate rooms for separate purposes — a module has a separate file for a specific task.

You can create a module for some specific job, and whenever you need it somewhere in your code — you just use it. Simple as that.

And how do you "use it"? Two magic words — IMPORT and EXPORT.


Without Modules vs With Modules

Without Modules With Modules
Code structure Everything in one file Separate file for each task
Readability Messy and hard to read Clean and easy to understand
Finding bugs Like finding a needle in a haystack Easy to isolate and fix
Reusing code Copy paste everywhere 😅 Just import wherever you need
Team work Everyone edits same file = chaos Everyone works on their own file
File size One giant file Small focused files

Export — Sharing Your Code

Let's say you wrote an add function in a file called math.js and you want to use it somewhere else.

First, you have to export it. Why? Because by default, everything in a file is private. Nobody outside can see it unless you export it.

There are two ways to export:

Named Export:

js

export function add(a, b) {}

Default Export:

js

export default function add(a, b) {}

Import — Using That Code

Once exported, you can bring it into any other file using import.

For Named Export:

js

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

Notice the curly braces {} — they are required for named exports.

For Default Export:

js

import add from './math.js';

No curly braces here — that's the difference!


The One Line Summary

Modules let you write clean, separated, reusable code — just like how your house has separate rooms for separate purposes.

That's it. That's modules. 🎯