Anti-Patterns in JavaScript: God Objects, Spaghetti and More
Anti-patterns are common solutions that cause more problems than they solve. See god objects, callback hell, magic strings and others in JavaScript with fixes.

An anti-pattern is a common response to a recurring problem that looks reasonable and reliably makes things worse. The term comes from a 1998 book on the subject, and the useful part of the idea is the recognition: when you can name the shape, you can spot it in review and fix it before it spreads. This post covers ten that show up constantly in JavaScript and TypeScript codebases on Node.js 24: the god object, spaghetti control flow, callback hell, magic strings and numbers, global mutable state, premature abstraction, copy-paste inheritance, the stringly typed API, swallowed errors and the boolean parameter. Each comes with a short example, what goes wrong and a fix. Every sample prints its output.
1. The god object
A single class or module that knows and does too much: it validates, stores, formats, emails and logs. Everything depends on it, so it changes for every reason.
const app = {
users: [],
addUser(name, email) {
if (!email.includes("@")) throw new Error("bad email");
this.users.push({ name, email });
console.log(`mail: welcome ${name}`);
return `<li>${name}</li>`;
},
};
console.log(app.addUser("Ada", "[email protected]"));mail: welcome Ada
<li>Ada</li>addUser validates, stores, sends mail and renders HTML. Testing the validation means mocking the mailer, and changing the markup means editing the same method as the storage. The fix is to split by reason to change: a validator, a repository, a notifier and a view function, composed by a small coordinator. See separation of concerns.
2. Spaghetti control flow
Deeply nested conditionals and early returns mixed with mutation, so that tracing one path means holding ten variables in your head.
function ship(order) {
let result = "none";
if (order) {
if (order.paid) {
if (order.items.length > 0) {
if (!order.address) {
result = "no address";
} else {
result = "shipped";
}
} else {
result = "empty";
}
} else {
result = "unpaid";
}
}
return result;
}
console.log(ship({ paid: true, items: [1], address: null }));no addressGuard clauses flatten it.
function ship(order) {
if (!order) return "none";
if (!order.paid) return "unpaid";
if (order.items.length === 0) return "empty";
if (!order.address) return "no address";
return "shipped";
}
console.log(ship({ paid: true, items: [1], address: null }));no addressSame behavior, one level deep, and the order of the checks reads like the business rules.
3. Callback hell
Nested callbacks, each depending on the last, produce a rightward pyramid and scattered error handling.
function getUser(id, cb) {
setTimeout(() => cb(null, { id, teamId: 7 }), 0);
}
function getTeam(id, cb) {
setTimeout(() => cb(null, { id, name: "Platform" }), 0);
}
getUser(1, (err, user) => {
if (err) return console.log(err);
getTeam(user.teamId, (err, team) => {
if (err) return console.log(err);
console.log(`${user.id} is on ${team.name}`);
});
});1 is on PlatformWith promises and async functions, the flow is linear and one try handles failure.
const getUser = async (id) => ({ id, teamId: 7 });
const getTeam = async (id) => ({ id, name: "Platform" });
try {
const user = await getUser(1);
const team = await getTeam(user.teamId);
console.log(`${user.id} is on ${team.name}`);
} catch (err) {
console.log(err);
}1 is on Platform4. Magic strings and numbers
Literals with hidden meaning, repeated across files.
function discount(user) {
if (user.tier === "gld") return 0.15;
if (user.age > 64) return 0.1;
return 0;
}
console.log(discount({ tier: "gold", age: 30 }));0The typo "gld" means gold customers silently get no discount, and no tool noticed. Name the values.
const Tier = Object.freeze({ GOLD: "gold", SILVER: "silver" });
const SENIOR_AGE = 65;
const SENIOR_DISCOUNT = 0.1;
function discount(user) {
if (user.tier === Tier.GOLD) return 0.15;
if (user.age >= SENIOR_AGE) return SENIOR_DISCOUNT;
return 0;
}
console.log(discount({ tier: "gold", age: 30 }));
console.log(discount({ tier: "silver", age: 70 }));0.15
0.1Naming also exposed that the original > 64 meant >= 65. In TypeScript, a string-literal union type, type Tier = "gold" | "silver", makes the typo a compile error.
5. Global mutable state
A shared object that any code may change makes behavior depend on call order and makes tests leak into each other.
export const config = { currency: "USD" };
function format(cents) {
return `${(cents / 100).toFixed(2)} ${config.currency}`;
}
console.log(format(1999));
config.currency = "EUR"; // somewhere far away
console.log(format(1999));19.99 USD
19.99 EURThe same call returned different results, and the cause is in unrelated code. Pass configuration in as an argument, or freeze it after startup, with Object.freeze for a shallow lock. See dependency injection.
6. Premature abstraction
A generic framework built before there are two real uses. The abstraction guesses wrong about what varies, and every real case must bend around it.
function createProcessor({ steps, onError, retries = 0, hooks = {}, transform = (x) => x }) {
return (input) => transform(steps.reduce((acc, step) => step(acc), input));
}
const processor = createProcessor({ steps: [(x) => x + 1] });
console.log(processor(1));2This is x + 1 with unused options, onError, retries and hooks, that nobody implemented. The better path is duplication first: write the second case by hand, notice what actually differs and abstract then. Three similar lines are often cheaper than one wrong abstraction. See YAGNI.
7. Inheritance for reuse
Extending a class to borrow a method, even though the subclass is not a kind of the parent.
class Logger {
log(msg) {
console.log(`[log] ${msg}`);
}
}
class OrderService extends Logger {
place() {
this.log("order placed");
}
}
const service = new OrderService();
service.place();
console.log(service instanceof Logger);[log] order placed
trueAn OrderService is not a Logger, and now Logger's methods are part of its public surface. Compose instead: give the service a logger.
class OrderService {
constructor(logger) {
this.logger = logger;
}
place() {
this.logger.log("order placed");
}
}
new OrderService({ log: (m) => console.log(`[log] ${m}`) }).place();[log] order placed8. Stringly typed APIs
Passing structured data as a string that every consumer must parse, such as "2026-11-20|paid|29.00". Each consumer re-parses it, and a format change breaks all of them silently. Use objects with named fields, and a schema at the boundary.
const row = "ada|36|true";
const [name, age, active] = row.split("|");
console.log(active === true, typeof age);
const person = { name: "ada", age: 36, active: true };
console.log(person.active === true, typeof person.age);false string
true numberAfter splitting, active is the string "true", not a boolean, so the comparison is false, and age is a string. Structured values keep their types.
9. Swallowed errors
An empty catch hides failures until they show up as mysterious wrong behavior later.
function readSetting(json) {
try {
return JSON.parse(json).timeout;
} catch {
return undefined;
}
}
console.log(readSetting('{"timeout": 30}'));
console.log(readSetting('{"timeout": 30,}'));30
undefinedA trailing comma made the config invalid, and the program continued with no timeout and no warning. Catch only what you can handle, log or rethrow the rest. See fail fast.
10. The boolean parameter
A call like render(user, true, false) says nothing at the call site, and flipping a flag is silent. Use an options object with named fields, as described in the principle of least astonishment.
How to use this list
Anti-patterns are diagnoses, not accusations. Each one began as a reasonable shortcut, and most are fine in a short script. The signal that one matters is cost: changes that take longer than they should, bugs that recur, tests that need heavy setup. When you spot one, fix the instance you are touching, with a small refactor in the same pull request, and let the rest wait. A rewrite aimed at "removing all anti-patterns" usually creates new ones.
Where the advice stops
Some of these have legitimate uses. A small global constant object is fine. A callback is the right shape for an event listener. Inheritance is right when the subclass truly is a kind of the parent and honors its contract. The label tells you where to look, and the judgment about cost is still yours.
Finding them in a codebase
You can look for several of these mechanically before you read any code. Sort files by size and open the largest: god objects live there. Search for catch { and catch (e) {} to find swallowed errors. Search for repeated literals, using a command such as grep -rhoE '"[a-z_]{3,}"' src | sort | uniq -c | sort -rn | head, to spot magic strings that should be constants. Look at the import graph for a module that imports from almost everywhere or is imported by almost everything, which marks a coordination point that has grown too large. A short pass like this takes a few minutes and usually produces a list longer than anyone wants to fix, which is why the next section matters.
Fixing them without a rewrite
Prefer small, safe steps. For a god object, extract one responsibility at a time behind the existing interface: move validation into its own function, leave a call to it where the code was, run the tests and commit. Repeat until what is left is a coordinator. For global state, wrap access in a function first, so every read and write goes through one place, then narrow it. For callback hell, convert one function to return a promise with util.promisify and leave callers alone until you touch them. Each step is reversible and each keeps the system working, which is what makes the cleanup possible in a codebase that is under active development.


