JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 15: Interactive Application ArchitectureLesson 75 of 150About 55 minutes

Lesson 75: Building maintainable browser applications

01Opening question

Your browser app works today. Will you, or a teammate, still understand and safely change it in six months?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

A maintainable app has a clear shape: configuration in one place, logic separate from views, and a single start-up function.

const App = {
  config: { storageKey: "notes:v1", pageSize: 5 },
  logic: { count: (notes) => notes.length },
  start(root) {
    root.textContent = "Notes app ready (" + this.logic.count([]) + " notes)";
  }
};
App.start(document.querySelector("#app"));
console.log(document.querySelector("#app").textContent);

03Objective and prerequisites

Learning objective: Organise a complete browser application with configuration, a store, pure logic, components, persistence and error handling, and apply a maintainability checklist.

You need: Lesson 74: Filtering, searching and pagination, Lesson 71: Separating data, logic and presentation, Lesson 72: Reusable UI components, Lesson 73: State-driven rendering

Skills practised: Browser application architecture, Maintainable applications.

04Explanation

Maintainable code is code that is easy to read, change and check. It matters more than clever code, because most time is spent changing existing programs.

Give the app a clear structure: config (constants), state/store, logic (pure rules), components (views), persistence (storage) and a start function that wires them together.

Use descriptive names, small functions with one job, and no "magic numbers": put values like the page size or storage key in config.

Handle failure: storage may be unavailable, saved data may be invalid, and user input may be odd. The app should keep working and tell the person what happened.

05Definitions

Maintainability
How easily code can be understood, changed and verified over time.
Configuration
Named constants and settings kept in one place instead of scattered literal values.
Dependency injection
Passing the things a function or module needs as parameters instead of reaching for globals.
Data migration
Converting saved data from an older format to the current one when it is loaded.
Magic number
An unexplained literal value in code whose meaning is not obvious from its context.

Open the full glossary

06Visual learning object

Responsive application preview. Run a small complete app at phone, tablet and desktop widths and inspect its layers: config, store, logic, components and storage.

Loading the interactive object…

Open the full Responsive application preview page with its guided experiment.

07Examples

ex-075-01The shape of a small app Browser page (sandboxed preview)

Each part has one job; start wires them together.

const config = { storageKey: "tasks:v1" };
const logic = {
  add: (tasks, title) => [...tasks, { id: tasks.length + 1, title, done: false }],
  remaining: (tasks) => tasks.filter((t) => !t.done).length
};
function createStorage(store, key) {
  return {
    load() { try { return JSON.parse(store.getItem(key)) ?? []; } catch { return []; } },
    save(value) { try { store.setItem(key, JSON.stringify(value)); } catch {} }
  };
}
function TaskSummary(tasks) {
  return Object.assign(document.createElement("p"), { textContent: logic.remaining(tasks) + " remaining" });
}
function start(root, storage) {
  let tasks = storage.load();
  tasks = logic.add(tasks, "Write README");
  storage.save(tasks);
  root.replaceChildren(TaskSummary(tasks));
}
start(document.querySelector("#app"), createStorage(localStorage, config.storageKey));
console.log(document.querySelector("#app").textContent, localStorage.getItem(config.storageKey));
Sample input
None
Expected output
1 remaining [{"id":1,"title":"Write README","done":false}]
Common mistake
Reaching for localStorage directly inside every function, which makes testing and changing storage hard.
Try this
Pass a fake storage object into start and check what it saved.
Source
examples/ex-075-01-structure.js

ex-075-02Testing with fake dependencies Browser page (sandboxed preview)

Because storage is passed in, a memory fake can stand in for it.

function createCounterApp(root, storage) {
  let n = Number(storage.getItem("n") ?? 0);
  const render = () => { root.textContent = "Count: " + n; };
  return {
    inc() { n++; storage.setItem("n", String(n)); render(); },
    render
  };
}
const memory = new Map();
const fakeStorage = { getItem: (k) => memory.get(k) ?? null, setItem: (k, v) => memory.set(k, v) };
const root = document.createElement("div");
const app = createCounterApp(root, fakeStorage);
app.render();
app.inc();
app.inc();
console.log(root.textContent, memory.get("n"), localStorage.length);
Sample input
None
Expected output
Count: 2 2 0
Common mistake
Hard-coding document.querySelector and localStorage inside the app, so the only way to test it is a real page.
Try this
Create two independent apps with two fake storages.
Source
examples/ex-075-02-fake-deps.js

ex-075-03Versioned data and migration Browser page (sandboxed preview)

Old saved data is upgraded on load instead of breaking the app.

const CURRENT = 2;
function migrate(data) {
  if (Array.isArray(data)) data = { version: 1, notes: data };
  if (data.version === 1) data = { version: 2, notes: data.notes.map((text) => ({ text, pinned: false })) };
  return data.version === CURRENT ? data : { version: CURRENT, notes: [] };
}
function load(key) {
  try { return migrate(JSON.parse(localStorage.getItem(key)) ?? { version: CURRENT, notes: [] }); }
  catch { return { version: CURRENT, notes: [] }; }
}
localStorage.setItem("notes", JSON.stringify(["Buy milk", "Call Li"]));
console.log(JSON.stringify(load("notes")));
localStorage.setItem("notes", "{broken");
console.log(JSON.stringify(load("notes")));
Sample input
None
Expected output
{"version":2,"notes":[{"text":"Buy milk","pinned":false},{"text":"Call Li","pinned":false}]} {"version":2,"notes":[]}
Common mistake
Changing the saved format in a new release without handling data saved by the old one.
Try this
Add version 3, which adds a createdAt field.
Source
examples/ex-075-03-migration.js

ex-075-04Failing gracefully Browser page (sandboxed preview)

One error boundary keeps the app usable and tells the person what happened.

function safely(fn, onError) {
  return (...args) => {
    try {
      return fn(...args);
    } catch (error) {
      onError(error);
    }
  };
}
const showError = (error) => {
  document.querySelector("#error").textContent = "Something went wrong: " + error.message;
  console.log("logged:", error.name);
};
const renderPrice = safely((product) => {
  document.querySelector("#app").textContent = product.name + ": $" + product.price.toFixed(2);
}, showError);
renderPrice({ name: "Lamp", price: 30 });
renderPrice({ name: "Mystery" });
console.log(document.querySelector("#app").textContent, "|", document.querySelector("#error").textContent);
Sample input
None
Expected output
logged: TypeError Lamp: $30.00 | Something went wrong: Cannot read properties of undefined (reading 'toFixed')
Common mistake
Letting one bad record throw and leave the whole page blank.
Try this
Validate the product before rendering instead of relying on the catch.
Source
examples/ex-075-04-errors.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Name the magic numbers

Move literals into configuration.

function shippingCost(subtotal) {
  return subtotal >= 75 ? 0 : 9.5;
}
console.log(shippingCost(80), shippingCost(20));
console.log(typeof CONFIG === "object" ? CONFIG.freeShippingFrom : "no config");

Inject the storage

Pass a dependency instead of using a global.

function createRecent(storage, key, max) {
  // TODO: return { add(term), list() } using only the storage passed in.
  // list() returns the saved array (newest first) or [].
  // add(term) puts term first, removes duplicates and keeps at most max.
}
const memory = {};
const fake = { getItem: (k) => memory[k] ?? null, setItem: (k, v) => { memory[k] = v; } };
const recent = createRecent(fake, "recent", 3);
for (const t of ["lamp", "mug", "lamp", "desk", "rug"]) recent.add(t);
console.log(recent.list().join(", "), memory.recent);

A complete mini app

Assemble config, logic, store, components and persistence.

// Build startApp(root, storage):
//  config: key "habits:v1"
//  logic:  toggle(habits, id) -> new array with done flipped;
//          progress(habits) -> "2/3 done"
//  persistence: load (JSON, [] on error) and save via the storage passed in
//  view: a ul of buttons (one per habit, text "✓ Name" or "○ Name",
//        aria-pressed) and a p with progress; one delegated click listener
//  start: if nothing is saved, use [{id:1,name:"Walk"},{id:2,name:"Read"},
//        {id:3,name:"Water"}] all not done.
// Run with localStorage, click Walk and Water, log the p text and the
// saved JSON's length (number of habits).

09Prediction

Commit to an answer first, then run the real code to compare.

const config = Object.freeze({ pageSize: 10 });
try {
  config.pageSize = 50;
} catch (e) {
  console.log(e.name);
}
console.log(config.pageSize);

What is printed (the code runs in strict mode)?

10Debugging investigation

The second widget shows the first widget's data

Two favourite-list widgets should each save their own data. Adding to the second widget changes what the first one shows.

function createFavourites(root) {
  const load = () => JSON.parse(localStorage.getItem("favourites") ?? "[]");
  function render() { root.textContent = root.id + ": " + load().join(", "); }
  return {
    add(item) {
      localStorage.setItem("favourites", JSON.stringify([...load(), item]));
      render();
    },
    render
  };
}
const a = createFavourites(document.getElementById("w1"));
const b = createFavourites(document.getElementById("w2"));
a.add("Tea");
b.add("Mug");
a.render();
console.log(document.getElementById("w1").textContent + " | " + document.getElementById("w2").textContent);

More cases in the Debugging Detective Laboratory

11Practical scenario

Handing over a project

A developer leaves a team. Because the app has a README, a config file, pure logic with checks, components that receive their dependencies, and versioned storage with migrations, the next developer ships a new feature in their first week instead of rewriting the app.

const checklist = ["README", "config", "pure logic + checks", "components", "injected deps", "versioned storage", "error handling"];
console.log(checklist.map((c, i) => i + 1 + ". " + c).join("\n"));

12Knowledge check

1. What does maintainability mean?

  • Code runs fast
  • Code is easy to understand, change and verify over time
  • Code is short
  • Code uses many libraries

2. Why pass storage into a module instead of using localStorage directly?

  • localStorage is slow
  • It allows fakes in tests and other storage later
  • It is required
  • It saves memory

3. Why does the app crash for people who used the old version?

const notes = JSON.parse(localStorage.getItem("notes"));
notes.items.forEach(render); // old versions saved a plain array
  • Saved data is in an old format and is not migrated
  • JSON.parse is broken
  • The key is too long
  • Storage is full

4. What is a magic number?

  • A random number
  • An unexplained literal value whose meaning is not obvious
  • A constant in CONFIG
  • A large number

5. safely(fn, onError) wraps a function that throws TypeError. What happens when it is called?

  • The page crashes
  • onError receives the error and the app keeps running
  • Nothing is logged
  • The error is rethrown

6. Which is easier for a new teammate?

  • One 900-line script with globals
  • Config, logic, components, persistence and a start function, with a README
  • Many files with copied code
  • Code with no comments or names

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Name the magic numbers: Prints the costs and config; Uses CONFIG
  • Inject the storage: Prints the recent list; Does not touch localStorage; Bad stored data gives []
  • A complete mini app: Prints 2/3 done 3; Buttons show state; Works with a fake storage

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-15-interactive-application-architecture/lesson-075-building-maintainable-browser-applications/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Structure apps into config, state, logic, components, persistence and start-up.
  • Inject dependencies so parts can be tested and replaced.
  • Version stored data and fail gracefully.
  • Names, small functions and one consistent style make code easy to change.

Suggested next lesson

Lesson 76: Synchronous and asynchronous execution planned

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation maintainable browser applications
Context: I am learning maintainable browser applications in JavaScript.
Task: Explain how to structure a small browser app into config, logic, components, persistence and start-up.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction maintainable browser applications drill
Context: I have practised maintainable browser applications.
Task: Give me six code snippets and ask what makes each easy or hard to maintain.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging maintainable browser applications bug
Context: My app breaks for returning users after I changed the saved data format.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation maintainable browser applications practice
Context: I finished the maintainable browser applications exercises.
Task: Create three exercises that refactor a small app for maintainability.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review maintainable browser applications review
Context: Here is my code that uses maintainable browser applications.
Task: Review my browser app's structure and give me a prioritised maintainability checklist.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.