🚀 Writing cleaner, scalable JavaScript starts with small habits.

📘 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,
});

Leave a Reply