Structuring a JavaScript Application

Updated · 9 min read
hardES2026javascriptarchitecturemodulesproject-structure

Application structure is how a program's code is divided into files and layers, and how those parts depend on each other. A 50-line script can live in one file; a real application with forms, data loading, business rules and storage can't, or every change risks breaking something unrelated. The most important idea is separation of concerns: business rules shouldn't know about the DOM, and the DOM code shouldn't contain business rules. This lesson presents a practical structure for front-end JavaScript apps, using the Fee Tracker's final layout as the example.

In One Minute

  • Separate UI (DOM, events), logic (pure business rules) and data (storage, network) into different modules.
  • Dependencies point inward: UI uses logic and data; logic depends on nothing.
  • Group files by feature (payments, students, reports) once the app grows; share common helpers.
  • Keep configuration (API URLs, limits) in one module; keep secrets out of the front end.
  • Use one consistent error-handling and logging approach.
  • The entry file wires everything together and stays small.

Three Layers

LayerContainsKnows aboutEasy to test?
UI (presentation)DOM updates, event listeners, formatting for displayLogic and data layersWith a DOM (browser or jsdom)
Logic (domain)Business rules: fees, validation, totals, statusNothing outside itselfYes: plain functions and data
Data (infrastructure)fetch, localStorage, IndexedDB, file accessFormats, endpointsWith mocks or fakes
Dependency direction
   ui/  ──────────▶  domain/  ◀──────────  data/
 (DOM, events)     (pure rules)       (fetch, storage)
          \                                   ▲
           └───────────────────────────────────┘
                 ui calls data to load and save

Domain code is the heart of the app and depends on nothing: no document, no fetch, no localStorage. That makes it fast to test, easy to reuse (the same lateFee runs in the browser, on a Node.js server and in a ServiceNow script), and safe from changes in the UI framework or the API.

A Folder Layout

For a small to medium front-end app, the Fee Tracker uses this structure:

Fee Tracker folders
fee-tracker/
├── index.html
├── package.json
├── src/
│   ├── main.js                  entry point: wires layers together
│   ├── config.js                settings (API base URL, limits)
│   ├── domain/                  pure logic, no DOM or network
│   │   ├── money.js             toCents, formatUsd
│   │   ├── fees.js              lateFee, balance, applyDiscount
│   │   └── validation.js        parsePayment
│   ├── data/                    talking to the outside world
│   │   ├── api.js               fetch wrapper with timeouts and errors
│   │   └── storage.js           localStorage with JSON and defaults
│   ├── state/
│   │   └── store.js             app state and change notifications
│   ├── ui/                      DOM code, one file per area
│   │   ├── payment-form.js
│   │   ├── payment-list.js
│   │   └── totals-chart.js
│   └── shared/
│       ├── errors.js            custom error classes
│       └── log.js               one logging helper
└── test/
    ├── fees.test.js
    └── validation.test.js
FolderRule
domain/No imports from ui/ or data/; no browser globals
data/The only place that calls fetch or localStorage
ui/The only place that touches document
state/Holds current data; notifies listeners when it changes
shared/Small helpers used everywhere; no app logic

Layers or Features?

Organize by layer (above)Organize by feature
domain/fees.js, ui/payment-list.jspayments/fees.js, payments/list.js, payments/api.js
Clear for small appsScales better: each feature is self-contained
Changes to one feature touch several foldersChanges stay in one folder

Many teams start by layer and move to features (each with its own small domain, data and UI files) as the app grows. The dependency rule stays the same either way.

The Entry Point

main.js creates the pieces and connects them. It contains no logic of its own:

main.js
import { config } from "./config.js";
import { createApi } from "./data/api.js";
import { createStore } from "./state/store.js";
import { mountPaymentForm } from "./ui/payment-form.js";
import { mountPaymentList } from "./ui/payment-list.js";
import { log } from "./shared/log.js";
 
const api = createApi(config.apiBaseUrl);
const store = createStore();
 
mountPaymentForm(document.querySelector("#payment-form"), { store, api });
mountPaymentList(document.querySelector("#payments"), { store });
 
try {
  store.setPayments(await api.getPayments());
} catch (err) {
  log.error("Initial load failed", err);
  store.setError("Couldn't load payments. Try again later.");
}

Because dependencies are passed in ({ store, api }), each UI module can be tested with a fake store and a fake API, and the real ones can be swapped without touching the UI.

Configuration in One Place

config.js▶ Try it
const DEFAULTS = {
  apiBaseUrl: "/api",
  requestTimeoutMs: 8000,
  lateFee: { graceDays: 10, perDay: 2, cap: 30 },
  currency: "USD",
};
 
function loadConfig(overrides = {}) {
  const config = { ...DEFAULTS, ...overrides, lateFee: { ...DEFAULTS.lateFee, ...overrides.lateFee } };
  return Object.freeze(config);
}
 
const config = loadConfig({ requestTimeoutMs: 5000 });
console.log(config.requestTimeoutMs, config.lateFee.cap, Object.isFrozen(config));
Output
5000 30 true

All tunable values live in one frozen object, with defaults and overrides (for example, from a build-time environment variable or the server). No module hard-codes its own copy of the late fee cap.

One Error-Handling Strategy

Inconsistent error handling (some functions return null, some throw strings, some log and continue) makes bugs hard to find. Pick one approach:

LayerResponsibility
DomainThrows specific errors (ValidationError) for invalid input
DataConverts network and storage failures into app errors (NetworkError, HttpError with status), keeping the original as cause
UICatches errors at the edge of each user action, shows a helpful message, logs details
Global safety neterror and unhandledrejection listeners log anything missed
errors.js▶ Try it
class AppError extends Error {
  constructor(message, options) { super(message, options); this.name = this.constructor.name; }
}
class ValidationError extends AppError {}
class HttpError extends AppError {
  constructor(status, options) { super(`Request failed with HTTP ${status}`, options); this.status = status; }
}
 
function userMessage(err) {
  if (err instanceof ValidationError) return err.message;
  if (err instanceof HttpError && err.status === 401) return "Please sign in again.";
  if (err instanceof HttpError) return "The server had a problem. Please try again.";
  return "Something went wrong.";
}
 
console.log(userMessage(new ValidationError("Amount must be positive")));
console.log(userMessage(new HttpError(503)));
console.log(new HttpError(404).name);
Output
Amount must be positive
The server had a problem. Please try again.
HttpError

Logging

Route all logging through one small module, so you can change where logs go (console in development, a monitoring service in production) and redact sensitive fields in one place:

log.js▶ Try it
const LEVELS = ["debug", "info", "warn", "error"];
 
function createLogger({ minLevel = "info", sink = console.log } = {}) {
  const min = LEVELS.indexOf(minLevel);
  const write = (level) => (message, details) => {
    if (LEVELS.indexOf(level) < min) return;
    sink(`[${level.toUpperCase()}] ${message}${details ? " " + JSON.stringify(details) : ""}`);
  };
  return Object.fromEntries(LEVELS.map((l) => [l, write(l)]));
}
 
const log = createLogger({ minLevel: "info" });
log.debug("cache hit", { key: "totals" });
log.info("payment saved", { id: 7, amountCents: 12050 });
log.error("load failed", { status: 503 });
Output
[INFO] payment saved {"id":7,"amountCents":12050}
[ERROR] load failed {"status":503}

In Practice

The Fee Tracker's layers working together, compressed into one runnable example: pure domain functions, a data module with a fake API, a tiny store, and a "UI" that only formats and displays (here, with console.log standing in for the DOM):

layers.js▶ Try it
// domain/fees.js: pure
const lateFee = (daysLate, { graceDays, perDay, cap }) => Math.min(Math.max(daysLate - graceDays, 0) * perDay, cap);
const amountDue = (student, rules) => student.balance + lateFee(student.daysLate, rules);
 
// data/api.js: the only place that "talks to the network"
const createApi = (fetchStudents) => ({ getStudents: () => fetchStudents() });
 
// state/store.js: one source of truth with change listeners
function createStore() {
  let state = { students: [] };
  const listeners = new Set();
  return {
    get: () => state,
    set(patch) { state = { ...state, ...patch }; listeners.forEach((fn) => fn(state)); },
    subscribe: (fn) => listeners.add(fn),
  };
}
 
// ui/student-list.js: display only
const mountStudentList = (store, rules) =>
  store.subscribe(({ students }) => students.forEach((s) => console.log(`${s.name}: $${amountDue(s, rules)} due`)));
 
// main.js: wiring
const rules = { graceDays: 10, perDay: 2, cap: 30 };
const api = createApi(async () => [{ name: "Srihitha", balance: 85, daysLate: 16 }, { name: "Advitha", balance: 45, daysLate: 2 }]);
const store = createStore();
mountStudentList(store, rules);
store.set({ students: await api.getStudents() });
Output
Srihitha: $97 due
Advitha: $45 due

Each part could be replaced independently: a real fetch in createApi, real DOM rendering in mountStudentList, a framework's store, while the domain rules stay untouched and fully tested.

Common Mistakes

Business rules inside event handlers. They can't be tested or reused. Move them into domain functions.

fetch and localStorage calls scattered everywhere. Changing the API means editing many files. Centralize them in the data layer.

Magic numbers repeated across files. Put them in config.js.

Every module importing every other module. Keep dependencies flowing inward; avoid circular imports.

One giant app.js. Split by layer or feature as soon as it's hard to find things.

Practice

Challenge: This handler mixes everything. Extract a pure parseAmount(text) domain function that returns cents or throws a RangeError, and show it working on its own.

practice.js
button.addEventListener("click", () => {
  const n = Number(document.querySelector("#amount").value);
  if (!(n > 0)) { alert("bad"); return; }
  fetch("/api/pay", { method: "POST", body: JSON.stringify({ cents: Math.round(n * 100) }) });
});
Show solution
practice-solution.js▶ Try it
function parseAmount(text) {
  const n = Number(String(text).trim());
  if (!Number.isFinite(n) || n <= 0) throw new RangeError("Enter an amount greater than $0");
  return Math.round(n * 100);
}
 
console.log(parseAmount("120.50"), parseAmount(" 45 "));
try {
  parseAmount("abc");
} catch (err) {
  console.log(err.message);
}
Output
12050 4500
Enter an amount greater than $0

The click handler then becomes three lines: read the field, call parseAmount, pass the result to the data layer, and show any error in the page instead of with alert.

Quick check: Application structure

3 questions
1Which layer should contain the late fee calculation?
2Which direction should dependencies point?
3Where do fetch and localStorage calls belong?

Key Takeaways

ConcernLives in
Rules and calculationsdomain/
fetch, storagedata/
DOM and eventsui/
Current datastate/
Settingsconfig.js
Wiringmain.js

Was this tutorial helpful?

Lesson 130 of 139