Frontend Quick Tips #8 Handling Too Many Arguments in a Function

Photo of Bernard Klatka

Bernard Klatka

Updated Jan 9, 2023 • 3 min read
Image with code and colors

No one likes those big articles - that’s why we’re creating Quick Tips - short tips to change your developer's life from the moment you read them.

Those may be some patterns explained in JS code on real-life examples or some techniques for better code.

Problem:


Your function receives many arguments and it’s hard to remember the order or not clean to scale up.

You may also have problems with optional arguments.

You may have started with a small function but over time maybe you’ve added additional flags for some features?

Solution:

Combine arguments in and object

You may think it looks the same - however...!

  • You don’t have to remember the order of the arguments.
  • It’s easy to scale.
  • In case one of your arguments is optional, you won’t end up in calling printCustomerDetails('John', 'Doe', someValue, undefined, undefined, false, true) (undefined values just because you want to reach the nth argument).
  • If your IDE is not helping with argument names – you won’t have to remember what the 3rd argument was for. Was it isEmployed flag?

This is also helpful for components (regardless of the framework - although the example is in React), as it’s easier to change an interface (especially if you have some prop drilling) than to modify your property definitions.

code

Rather than passing property after property...

code

...pass an object containing all your props.

Guidelines when to use:

  • If you have a common data model.
  • For options/configuration objects - to allow optional options.
  • In a function - if you have more than 5 arguments.
  • In a component - when your component takes many properties from a single data model.

Important note

If you’re passing more than 5 arguments to a func/comp… you are probably doing something wrong and breaking the SOLID rule. Are you sure your method follows SRP?

Photo of Bernard Klatka

More posts by this author

Bernard Klatka

Read more on our Blog

Check out the knowledge base collected and distilled by experienced professionals.

We're Netguru

At Netguru we specialize in designing, building, shipping and scaling beautiful, usable products with blazing-fast efficiency.

Let's talk business