JavaScript Modules: A Beginner’s Guide

Untangling Code with Exports and Imports

Max N
2 min readFeb 9, 2024

JavaScript modules split code into separate files that explicitly export and import dependencies. This modular architecture makes applications easier to develop and maintain.

In this article, we’ll cover the basics of using modules to untangle JavaScript codebases.

Why JavaScript Needed Modules

Before modules, JavaScript projects would include many scripts that implicitly shared global variables. This caused problems:

  • Difficulty Managing Dependencies: No clarity on what code depends on what scripts.
  • Namespace Collisions: Scripts could accidentally overwrite global variables.
  • Hard to Reuse: No encapsulation of logic into components.

Modules solve these issues by allowing explicitly defined inter-module dependencies:

// module.js
export function add(a, b) {
return a + b;
}

// main.js
import {add} from './module.js';

add(1, 2); // 3

Much cleaner!

Using ES6 Export/Import

Modules leverage two new keywords:

  • export: Makes variables and functions available to other modules

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.