01 / 21

Organizing Code
into Modules

Learn how to split JavaScript programs into separate files using modules: export, import, and clean architecture patterns.

JavaScript

What Is a Module?

A module is a self-contained file of JavaScript code that exports specific values: functions, variables, or classes. Other files can then import only what they need.

Encapsulation
Each module hides its internal details and exposes only a public interface.
Reusability
Write a utility once, import it anywhere across your project.

Why Modules Matter

One Giant File 500+ lines, tangled → Modular Files math.js utils.js api.js ui.js app.js

Key Vocabulary

export
Makes a function, variable, or class available to other files.
import
Brings an exported value into the current file so you can use it.
default export
A single "main" value exported from a module. Each file can have at most one.

The Core Rule: export and import

math.js export function add(a, b) { return a + b; } export function multiply(a, b) { return a * b; } import app.js import { add, multiply } from './math.js'; console.log(add(2, 3)); // 5

Named vs Default Exports

Named Export Default Export
Syntax (export) export function add() {} export default function() {}
Syntax (import) import { add } from '...' import myFunc from '...'
Per file limit Unlimited Exactly one
Braces required? Yes { } No
Renaming import { add as sum } Any name you want

Module Dependency Graph

app.js auth.js api.js ui.js utils.js config.js

Each arrow represents an import statement. The entry point (app.js) imports from feature modules, which in turn import from shared utilities. This creates a clean, tree-shaped dependency graph.

How to Modularize Your Code

1
Identify responsibilities. Group related functions, classes, or constants that serve a single purpose.
2
Create a new file. Move the grouped code into its own .js file with a descriptive name (e.g., validation.js).
3
Add export keywords. Place export before each function or variable that other files need.
4
Import where needed. In the consuming file, write import { name } from './file.js'.
5
Test the connection. Run the code to confirm exports and imports are wired correctly.

Example 1: Named Exports

utils.js
export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

export function slugify(str) {
  return str.toLowerCase().replace(/\s+/g, '-');
}

export const MAX_LENGTH = 100;
app.js
import { capitalize, slugify, MAX_LENGTH }
  from './utils.js';

console.log(capitalize('hello'));   // "Hello"
console.log(slugify('My Post'));    // "my-post"
console.log(MAX_LENGTH);             // 100

Example 2: Default Export

Logger.js
export default class Logger {
  log(message) {
    console.log(`[LOG] ${message}`);
  }
  error(message) {
    console.error(`[ERR] ${message}`);
  }
}
app.js
import Logger from './Logger.js';

const logger = new Logger();
logger.log('App started');   // [LOG] App started

Example 3: Mixing Named + Default

math.js
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }

export default function calculate(op, a, b) {
  if (op === '+') return add(a, b);
  if (op === '-') return subtract(a, b);
}
app.js
import calculate, { add } from './math.js';

console.log(calculate('+', 5, 3));  // 8
console.log(add(10, 20));            // 30

Barrel Files: Re-exporting

A barrel file re-exports items from multiple modules through a single index.js entry point. This simplifies import paths for consumers.

utils/index.js
export { capitalize, slugify } from './strings.js';
export { add, multiply }      from './math.js';
export { API_URL }              from './config.js';
app.js
// One clean import instead of three separate ones
import { capitalize, add, API_URL } from './utils';

Module Scope and Privacy

helpers.js module scope Private (not exported) const SECRET = 'xyz'; function helper() { // internal logic } Public (exported) export function format() { return helper(); } export const VERSION = 2;

Project Folder Structure

my-app/
  src/
    components/
      Header.js
      Footer.js
      index.js        // barrel re-exports
    utils/
      math.js
      strings.js
      index.js        // barrel re-exports
    services/
      api.js
      auth.js
    app.js            // entry point
Group by feature
Put related files in the same folder: components together, utilities together.
Name clearly
File names should describe their content: auth.js not file2.js.

Common Mistakes

✕ Forgetting Braces
Writing import add from './math.js' instead of import { add } when add is a named export. Without braces, JS looks for a default export.
✕ Wrong File Path
Writing 'math.js' instead of './math.js'. Without ./, the runtime looks in node_modules, not your local folder.
✕ Circular Imports
File A imports from B, and B imports from A. This creates a cycle that can cause undefined values at runtime.

Module Syntax Cheat Sheet

Pattern Export Side Import Side
Named (single) export function fn() {} import { fn } from '...'
Named (multiple) export { a, b, c } import { a, b } from '...'
Default export default class X {} import X from '...'
Mixed export { a }; export default b; import b, { a } from '...'
Re-export export { x } from './other' import { x } from './barrel'
Rename export { fn as myFn } import { myFn } from '...'

Question 1 of 5

Which keyword makes a function available to other files in JavaScript ES modules?

Question 2 of 5

Given export function greet() {} in hello.js, which import statement is correct?

Question 3 of 5

How many default exports can a single JavaScript module file have?

Question 4 of 5

What is the purpose of a barrel file (like index.js) in a module folder?

Question 5 of 5

A variable declared inside a module without the export keyword is: