How would you structure JavaScript for a maintainable production application?
Quick Interview Answer
Detailed Explanation
A maintainable application separates responsibilities into clear modules and keeps dependencies explicit. Domain calculations should be separated from DOM manipulation, network access, storage, and other infrastructure where practical. State ownership and data flow should be understandable rather than spread across unrelated global variables.
Use consistent naming, small focused functions, clear error boundaries, secure handling of untrusted data, cancellation for obsolete asynchronous work, and tests for important behavior. Avoid premature abstractions, but remove repeated business rules that could diverge.
At production scale, use automated formatting and linting, appropriate type checking, unit and integration tests, dependency and security updates, code review, source maps, monitoring, performance measurement, and a build/deployment process matched to supported browsers. Architecture should remain proportional to application complexity rather than adding patterns only for appearance.
Code Example
// api/products.js
export async function getProducts(signal) {
const response = await fetch(
"/api/products",
{ signal }
);
if (!response.ok) {
throw new Error(
`HTTP ${response.status}`
);
}
return response.json();
}
// domain/products.js
export function getActiveProducts(products) {
return products.filter(
product => product.active
);
}
// ui/products.js
export function renderProducts(products) {
const list =
document.querySelector("#products");
list.replaceChildren(
...products.map(product => {
const item =
document.createElement("li");
item.textContent = product.name;
return item;
})
);
}