JavaScript Modules: Import and Export Explained

Why modules are needed
In the beginning, all your JavaScript code usually lives in one giant file. As your project grows, that file becomes a bit of a mess—often called "spaghetti code" by our coding communitiy. Finding a basic bug or adding a feature in the webpage becomes a nightmare because everything is like glued together in one JS file. Modules were introduced so we can break that giant JS files into small, organized, and independent pieces of different JS files.
Exporting functions or values
A module is basically a file that wants to share its code with other files. To share a function, variable, or object, we use the export keyword. Think of it like putting a "Public" label on a specific item in your shop so others can see it and take it.
Now we made different JS files but if we need the code of different file in an spcefic different file, we can share the code of other files by writing export and then writing the variable, function, expression, etc, you want to share with other code files and we'll see how to access this code in next section, this is the basic syntax of how to export something in JS:
JavaScript:
// math.js
export const add = (a, b) => a + b;
export const pi = 3.14;
Importing modules
Once we have exported something from a file, you need to import it into the file where you want to use its code. This tells JS exactly which function, expression, etc, you need and which file it is located in. This keeps your main JavaScript file clean because you only bring only the necessary items when required, basic syntax is given below:
JavaScript:
// main.js
import { add, pi } from './math.js';
console.log(add(2, 3)); // Output: 5
Default vs Named exports
There are two ways to share your code, and understanding the difference is key:
Named Export: You can export multiple things from one file. When importing them, you must use the exact names inside curly braces
{ }.Default Export: You can only have one default export per file. When importing it, you don’t need curly braces, and you can even give it a different name.
Benefits of modular code
Organization: Your code stays clean and easy to navigate, find bugs and add new features.
Reusability: You can write a function once and use it in many times in different files.
Maintainability: If there’s a bug in your math logic, you only check
math.js, not the whole project, which was a nightmare to do before modular code.No Conflicts: Two different files can have variables with the same name without crashing the app.
Modular code is like a well-organized toolbox: it takes a moment to set up, but it saves you hours of searching. Stop nesting and start exporting. Happy coding!
