π JavaScript Best Practice: Use Object Parameters Instead of Long Positional Arguments
β DONβT DO THIS β Positional Parameters
When a function has multiple parameters, especially optional ones, positional arguments become confusing and error-prone.
Bad Example
function saveUser(name, email, phone) {
// ...
}
// β Hard to read
saveUser("John", "", "9876543210");
// β What is ""? Which field did we skip?
Problems
- Hard to remember argument order
- Passing empty strings just to skip parameters
- Code becomes unreadable and brittle
- Adding new optional parameters breaks all existing calls
β DO THIS β Use a Single Object Parameter
Objects allow named parameters, optional values, default values, and cleaner code.
Good Example
function saveUser({ name, email, phone }) {
// ...
}
// β
Much clearer
saveUser({
name: "John",
phone: "9876543210",
});
Benefits
- No need to remember order
- Optional parameters become easy
- Extensible without breaking old code
- Self-documenting function calls
π‘ Real-World Production Examples
β Example 1: API Request Handler
β Old (positional hell)
function fetchUsers(page, limit, search, sortBy, direction) {
// ...
}
fetchUsers(1, 20, "", "name", "asc");
β New (object parameters)
function fetchUsers({
page = 1,
limit = 20,
search = "",
sortBy = "name",
direction = "asc",
}) {
// ...
}
fetchUsers({
search: "john",
direction: "desc",
});
β Example 2: Vue/React Component Utils
β Anti-pattern
function openModal(title, content, showClose, size) { }
openModal("Delete?", "Are you sure?", true, "lg");
β Clean pattern
function openModal({
title,
content,
showClose = true,
size = "md",
}) {}
openModal({
title: "Delete?",
content: "Are you sure?",
size: "lg",
});
β Example 3: Logging in Production
β Wrong
log("error", "Database failed", false, Date.now());
β Right
log({
level: "error",
message: "Database failed",
showAlert: false,
timestamp: Date.now(),
});
β Example 4: Utility Function
β Bad
function calculatePrice(price, discount, tax, includeGST) {}
calculatePrice(1000, 0, 5, true);
β Good
function calculatePrice({
price,
discount = 0,
tax = 5,
includeGST = false,
}) {}
calculatePrice({
price: 1000,
});
πΌ Production-Ready Template (Reusable)
/**
* @description Generic best-practice function with object params.
*/
function doTask({
required,
optional1 = "",
optional2 = null,
enabled = true,
}) {
// function logic
}
// Usage:
doTask({
required: "value",
enabled: false,
});
Top comments (0)