In C#, I often use named parameters like calculateBMI(70, height: 175)
—it’s super convenient. In JavaScript, I’ve been doing something like:
myFunction({ param1: 70, param2: 175 });
function myFunction(params) {
// validate param1 and param2 from the object
}
But honestly, this approach feels a bit awkward and repetitive.
Is there a better or more elegant pattern for working with JavaScript named parameters to make the code cleaner and more readable?
Hey! What you’re doing is actually a solid start.
To make it less awkward, you can use parameter destructuring directly in the function definition. It makes the code cleaner and self-documenting:
function myFunction({ param1, param2 }) {
if (!param1 || !param2) return;
// use param1 and param2 directly
}
This pattern is super readable and others on your team can instantly see what parameters are expected, no need to dig into the function body.
Also, pairing this with default values makes it even smoother for collaboration.
Hi @Ariyaskumar if you’re working with others or on a shared codebase, combining named parameters with JSDoc comments or even TypeScript types adds clarity:
/**
* @param {{ param1: number, param2: number }} params
*/
function myFunction({ param1, param2 }) {
// cleaner and easier for others to understand
}
Or with TypeScript:
function myFunction({ param1, param2 }: { param1: number, param2: number }) {
// all good here
}
It helps your teammates quickly see what’s expected, makes the function calls readable, and improves code hints in editors, a great collaborative win.
@Ariyaskumar If you’re doing this in a team environment and the functions get larger, one approach that helped us is defining a small config schema or using a validation library like zod or yup.
That way, you get both named parameters and structured validation without the manual checks.
js
Copy
Edit
import { z } from "zod";
const ParamsSchema = z.object({
param1: z.number(),
param2: z.number()
});
function myFunction(params) {
const validated = ParamsSchema.parse(params);
// safe to use param1 and param2 now
}
This helps a lot when multiple devs touch the same code and you want to avoid subtle bugs.
Everyone benefits from clearly defined expectations.