How to Write Good Functions in JavaScript
This article is a complementary resource to the Learn JavaScript Basics course.
This article is a complementary resource to the Learn JavaScript Basics course.
How to Write Good Functions in JavaScript
A JavaScript function is a block of code designed to perform a specific task.
Good functions form the foundation of clean, efficient, and reusable JavaScript code. By following best practices, you can create functions that are easy to understand, debug, and extend.
A function should perform one clear task. Avoid combining multiple unrelated tasks into a single function. For example,
Good: Single Responsibility
function calculateSum(a, b) {
let total = a + b;
return total;
}
Bad: Multiple Responsibilities
function processNumbersAndPrint(a, b) {
let total = a + b;
console.log("The sum is:", total);
return total;
}
In the good example, the function only calculates the sum, making it reusable in various contexts.
Use clear and descriptive names for your functions and parameters to indicate their purpose. Avoid vague names like doSomething() or overly short ones like x. For example,
Good: Descriptive Name
function getUserAge(user) {
return user.age;
}
Bad: Vague Name
function g(u) {
return u.a;
}
Descriptive names make your code easier to read and maintain, especially in larger projects.
Short functions are easier to read, test, and debug. Aim for 20–30 lines of code per function, and break complex tasks into smaller helper functions. For example,
// Break down tasks into smaller functions
function processOrder(order) {
validateOrder(order);
calculateTotal(order);
saveOrder(order);
}
// Helper functions for readability
function validateOrder(order) {
// Validation logic
}
function calculateTotal(order) {
// Calculation logic
}
function saveOrder(order) {
// Save logic
}
This approach aligns with the first point in this blog: ensuring that each function focuses on performing one task effectively.
A good function should rely on parameters for input and return values for output. Avoid using or modifying external variables inside the function, as this can lead to unexpected side effects and make the function harder to debug. For example,
Good: Only uses parameters
function calculateDiscount(price, discountRate) {
return price * discountRate;
}
Bad: Relies on outer variables
let discountRate = 0.1;
function applyDiscount(price) {
return price * discountRate;
}
Functions that only depend on their parameters are also less prone to bugs caused by unexpected changes in the surrounding environment.
Make your functions flexible and reusable by accepting parameters instead of hardcoding values. For example,
Good: Uses parameter
function greet(name) {
console.log(`Hi ${name}!`);
}
Bad: Uses hardcoded value
function greet() {
let person = "Emma"; // Hardcoded value
console.log(`Hi ${person}!`);
}
In the good example, the function can greet anyone by simply passing their name as a parameter, making it versatile and reusable. In contrast, the bad example is limited to always greeting "Emma", reducing its flexibility and usefulness in different contexts.