DEV Community

EidorianAvi
EidorianAvi

Posted on

Modular Javascript: An intro to import and export

ECMAScript6(ES6), the standardization of javascript, introduced the import and export functions to the language to encourage and facilitate modular programming(MP). I wanted to discuss what modular programming is and how it's handled in javascript.

So first off modular programming is a software design technique that breaks your code into seperate(or modular) components for the purpose of not only cleaning up but also creating interchangeable and reusable code. Imagine having a larger scale application or website with a lot of functionality and having hundreds of lines of code in one file to handle it all. It becomes difficult to navigate and is just unpleasant to have to sift through so much code whether it's your own code or not. Modular programming is the solution to such a circumstance and does wonders for your code. Now it's not a modern phenomenon in coding by any means in fact it's been around since the 80's but it's not incorporated into every coding language or necessary for all of them. It was however introduced to javascript in 2015 and is used in many if not all modern frameworks.

The whole idea behind MP is to separate your functions and components into their own files and only bringing them in when that sort of functionality is required. This makes your code highly reusable and easier to debug. Not only that but it makes your code easier to navigate and encourages the use of the single responsibility principle. It's a no brainer why javascript adopted it.

Javascripts way of handling MP was to introduce the import and export methods. When you're trying to use a function inside another file you must export it out of its location and import into the file where it's needed. Here's a basic example of how that would look.

In the example.js file I've added a very simple addition function. Notice how before the function prepend export

export function add(a, b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Now in the index.js file I first import the function by adding it in the curly brace like so

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

console.log(add(10 + 3))
Enter fullscreen mode Exit fullscreen mode

Now when I run the console log from the index.js file it runs and outputs 13 so the import worked even though the function is in a separate file. Now that's it to the absolute basics but that concept can be applied to giant functions or entire subsets of functions to keep your code organized, neat, and reusable.

Top comments (0)