Function Smells and How to Fix Them
Learn seven JavaScript function smells, from long parameter lists and boolean flags to hidden mutation, with a fix and output for each. Node.js 24.

A code smell is not a bug. It is a feature of the code that suggests a problem nearby, the way a smell in a kitchen suggests that something should be thrown out. Functions have their own smells, and they are easy to learn because they show up in the signature or the first screen of the body, before you read what the function does. This post lists seven smells that appear constantly in JavaScript and Node.js 24 codebases: long parameter lists, boolean flag arguments, functions that change their arguments, hidden dependencies, deep nesting, mixed return types and functions that do several jobs. Each comes with a short example, what goes wrong, the fix and the output of the fixed version. The goal is not to follow rules, but to recognize the pattern and ask whether it is costing you. For testing the result of such refactors, see writing functions that are easy to test.
1. A long parameter list
Five or six positional parameters are hard to call correctly, since the reader cannot tell what each value means.
function createUser(name, email, age, isAdmin, sendWelcome, locale) {
return { name, email, age, isAdmin, sendWelcome, locale };
}
console.log(createUser("Ada", "[email protected]", 36, true, false, "en"));{
name: 'Ada',
email: '[email protected]',
age: 36,
isAdmin: true,
sendWelcome: false,
locale: 'en'
}At the call site, true, false tells you nothing, and swapping them compiles and runs. The fix is an options object, so each value is named where it is passed.
function createUser({ name, email, age, isAdmin = false, sendWelcome = true, locale = "en" }) {
return { name, email, age, isAdmin, sendWelcome, locale };
}
console.log(createUser({ name: "Grace", email: "[email protected]", age: 85, isAdmin: true }));{
name: 'Grace',
email: '[email protected]',
age: 85,
isAdmin: true,
sendWelcome: true,
locale: 'en'
}The call now documents itself, order no longer matters and a new optional field can be added without breaking callers. If the list is long because the function takes several related values, such as a name, an email and an age that always travel together, consider whether they are one concept and should be one parameter.
2. A boolean flag argument
A boolean parameter that switches the function between two behaviors usually means two functions in a trench coat.
function render(items, asHtml) {
if (asHtml) return `<ul>${items.map((i) => `<li>${i}</li>`).join("")}</ul>`;
return items.join(", ");
}
console.log(render(["a", "b"], true));
console.log(render(["a", "b"], false));<ul><li>a</li><li>b</li></ul>
a, bThe call render(items, true) is unreadable without looking up the signature, and the function has two reasons to change. Split it by what it does.
const renderHtml = (items) => `<ul>${items.map((i) => `<li>${i}</li>`).join("")}</ul>`;
const renderText = (items) => items.join(", ");
console.log(renderHtml(["a", "b"]));
console.log(renderText(["a", "b"]));<ul><li>a</li><li>b</li></ul>
a, bEach function does one thing, has a name that says which, and can be tested alone. If the flag chooses among several behaviors, pass the behavior as a function or use a lookup of formatters keyed by name.
3. Changing the arguments
A function that modifies an object it receives surprises its caller, who usually expects the call to be a question and not a command.
function applyDiscount(order, rate) {
order.total = order.total * (1 - rate);
return order;
}
const order = { id: 1, total: 100 };
const discounted = applyDiscount(order, 0.2);
console.log(order.total, discounted === order);80 trueThe caller's order changed, and the returned value is the same object, so a program that wanted to compare the original and the discounted price has lost the original. The fix is to return a new object and leave the argument alone.
function applyDiscount(order, rate) {
return { ...order, total: order.total * (1 - rate) };
}
const original = { id: 1, total: 100 };
const cheaper = applyDiscount(original, 0.2);
console.log(original.total, cheaper.total, cheaper === original);100 80 falseBoth values exist, and nothing else in the program changed behind anyone's back. Mutation is fine inside a function on its own local data. The smell is mutation of what was passed in.
4. Hidden dependencies
A function that reads a global, the clock or the environment cannot be understood or tested from its signature.
function isExpired(token) {
return token.expiresAt < Date.now();
}
console.log(isExpired({ expiresAt: 0 }));trueThat works until you test the boundary: to check that a token expires exactly at some time you must freeze or mock the clock. Make the dependency a parameter, with the real clock as the default.
function isExpired(token, now = Date.now()) {
return token.expiresAt <= now;
}
console.log(isExpired({ expiresAt: 1000 }, 999));
console.log(isExpired({ expiresAt: 1000 }, 1000));false
trueThe boundary is now a plain test with two numbers. The same move works for random numbers, configuration and services: pass them in, and default to the real thing so callers who do not care need not change.
5. Deep nesting
Many levels of if make the interesting line the hardest to find.
function ship(order) {
if (order) {
if (order.paid) {
if (order.items.length > 0) {
return "shipped";
} else {
return "empty";
}
} else {
return "unpaid";
}
}
return "no order";
}The fix is guard clauses: handle each unusual case first and return early, so the main path runs at the left margin.
function ship(order) {
if (!order) return "no order";
if (!order.paid) return "unpaid";
if (order.items.length === 0) return "empty";
return "shipped";
}
console.log([undefined, { paid: false, items: [] }, { paid: true, items: [] }, { paid: true, items: [1] }].map(ship));[ 'no order', 'unpaid', 'empty', 'shipped' ]The four outcomes read top to bottom, and each condition sits next to the result it produces. Behavior is identical to the nested version. A function that needs more than two levels of indentation is usually a candidate for early returns or for extracting an inner block into its own function.
6. Inconsistent return types
A function that returns a number sometimes and undefined, a string or an array at other times forces every caller to check.
function findPrice(items, name) {
const item = items.find((i) => i.name === name);
if (!item) return "not found";
return item.price;
}
const total = findPrice([{ name: "pen", price: 2 }], "ink") + 1;
console.log(total);not found1The error message was treated as a price and joined to a number as text, which is a wrong answer with no error. Return one type, and signal absence in a way that cannot be mistaken for data: undefined, a null or a thrown error, depending on whether absence is expected.
function findPrice(items, name) {
return items.find((i) => i.name === name)?.price;
}
const price = findPrice([{ name: "pen", price: 2 }], "ink");
console.log(price, price ?? "no price");undefined no priceThe function now returns a number or undefined, and the caller decides with ??. In TypeScript the type number | undefined forces the check. A function that sometimes returns a promise and sometimes a plain value has the same smell, and the fix is to make it always async.
7. A function that does several jobs
A function whose name needs an "and", or whose body has comment headers for its sections, is several functions.
function processOrder(order) {
// validate
if (!order.items.length) throw new Error("empty order");
// price
const total = order.items.reduce((sum, i) => sum + i.price, 0);
// format
return `Order ${order.id}: ${total.toFixed(2)}`;
}
console.log(processOrder({ id: 7, items: [{ price: 4.5 }, { price: 5.25 }] }));Order 7: 9.75Each comment marks a function that wants to exist. Split them, and keep the original as a short composition of the pieces.
const validate = (order) => {
if (!order.items.length) throw new Error("empty order");
return order;
};
const price = (order) => order.items.reduce((sum, i) => sum + i.price, 0);
const format = (order, total) => `Order ${order.id}: ${total.toFixed(2)}`;
const processOrder = (order) => format(validate(order), price(order));
console.log(processOrder({ id: 7, items: [{ price: 4.5 }, { price: 5.25 }] }));Order 7: 9.75The result is the same, and now pricing can be tested without validation or formatting, and formatting can change without touching the arithmetic. The top-level function reads like a sentence.
Smells that travel together
Smells rarely appear alone, and noticing the cluster helps you pick the first fix. A function with a boolean flag, several jobs and deep nesting is usually one function that grew by accumulating cases, and the first move is to split it by job, after which the flag and the nesting often disappear on their own. A function with hidden dependencies and a long parameter list is often a method pretending to be a function: it needs a handful of things from its surroundings and receives half of them through arguments and half through globals. Gathering those into an explicit object, passed in, is the remedy.
Tests help you decide. If a function needs a long setup to run, count what the setup creates: each item is a hidden dependency or an overloaded responsibility. If a function has so many branches that you need dozens of cases, it is doing too much. The pain of writing the test is the same signal as the smell, felt earlier.
Knowing when to leave it alone
A smell is a prompt to look, not an instruction to change. A function with six parameters that is called in one place and never changes is not worth the refactor. A boolean flag in a two-line helper is fine. Fix smells where the code changes often, where bugs have appeared or where a new teammate got confused, and leave stable code alone. And fix one smell at a time, with the tests passing between steps, so that a behavior change cannot hide inside a cleanup.


