How to Write Clean Functions in JavaScript
Learn how to write clean JavaScript functions that are easy to read, test, and maintain. This guide covers naming, single responsibility, pure functions, and avoiding common pitfalls.
Clean JavaScript functions are the foundation of maintainable code. A function that does one thing, has a clear name, and doesn’t surprise you is worth more than a clever function that does everything. Here’s how to write them.
One Function, One Job
The Single Responsibility Principle applies to functions: a function should do exactly one thing. If you find yourself using “and” to describe what a function does, split it.
// Bad — does too much
function processUser(user) {
const validated = user.email.includes("@") && user.age > 0;
if (validated) {
fetch("/api/users", { method: "POST", body: JSON.stringify(user) });
sendWelcomeEmail(user.email);
logEvent("user_created");
}
}
// Good — split into focused functions
function isValidUser(user) {
return user.email.includes("@") && user.age > 0;
}
async function saveUser(user) {
return fetch("/api/users", { method: "POST", body: JSON.stringify(user) });
}
Name Functions for What They Do
Function names should be verbs or verb phrases. Be specific:
// Vague
function process(data) {}
function handle(event) {}
// Clear
function parseCSVRow(row) {}
function handleFormSubmit(event) {}
function formatCurrency(amount, currency) {}
function isValidEmail(email) {}
Boolean-returning functions should start with is, has, or can.
Pure Functions Are Easier to Test
A pure function always returns the same output for the same input and has no side effects:
// Pure — no external state, no side effects
function calculateDiscount(price, percent) {
return price * (1 - percent / 100);
}
// Impure — depends on external state
let discountRate = 10;
function calculateDiscount(price) {
return price * (1 - discountRate / 100); // depends on external variable
}
Pure functions are trivial to test and predictable. Prefer them for business logic.
Keep the Argument Count Low
Functions with many parameters are hard to call correctly. Prefer an options object for three or more arguments:
// Hard to call correctly — what order are these?
createUser("Kaikobud", "kai@kaiko.dev", true, "admin", "Dhaka");
// Clear and extensible
createUser({
name: "Kaikobud",
email: "kai@kaiko.dev",
active: true,
role: "admin",
city: "Dhaka"
});
Conclusion
Writing clean JavaScript functions is a habit, not a talent. Follow these four rules: one job per function, clear verb names, prefer pure functions for logic, and use options objects for many parameters. Apply them consistently and your codebase becomes dramatically easier to read and maintain.
Read next: JavaScript Error Handling: try, catch, and finally
External resource: Clean Code JavaScript — GitHub
Related Articles
async/await in JavaScript: Making Async Code Readable
Learn how async/await in JavaScript works with clear examples. Understand how it replaces Promise chains, handles errors with try/catch, and makes asynchronous code easier to read.
CSS Flexbox in Plain English: A Beginner's Guide
Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.
CSS Grid vs Flexbox: When to Use Which
Learn when to use CSS Grid vs Flexbox with clear examples. Understand the key differences between one-dimensional and two-dimensional layouts to make the right choice every time.