Learning objective: Organise a complete browser application with configuration, a store, pure logic, components, persistence and error handling, and apply a maintainability checklist.
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.
Make dependencies explicit: pass the store, storage and root element into the parts that need them. That keeps modules testable with fakes (a memory storage object, a detached element).
Version persisted data and migrate it on load. Validate everything that crosses a boundary: storage, URL parameters, network responses and form input.
Write quick checks for the logic layer now, and a real test runner later (Level 5 covers automated testing). Keep a short README describing structure, commands and decisions.
Consistency beats preference: one way to render, one way to name events, one place for configuration. Linters and formatters enforce this automatically in a team.
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.
Responsive application preview. Run a small complete app at phone, tablet and desktop widths and inspect its layers: config, store, logic, components and storage.
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.
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.
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
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.
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.
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.
Debuggingmaintainable 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 generationmaintainable 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.
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.