Increase Readability of Function Calls in JavaScript with an Argument Object

An argument object is a pattern to create more readable code involving function calls.

As the number of function arguments increases, readability rapidly declines.

We can create cleaner code by using an argument object: an object with keys for each function parameter. The reader does not have to inspect or deduce the meaning of positional arguments.

Suppose we have a function to locate a point based on latitude and longitude, but also with a radius and a flag indicating placing a marker.

A function call would look like this:

geoLocate(40.730610, -73.935242, 100.0, true);

Coming across the above call in code would require digging into the meaning of each positional argument.

We can make this more readable by making the function accept an argument object instead as below:

  lat: 40.730610,
  lng: -73.935242,
  radius: 100.0,
  placeMarker: true 

This approach is especially helpful with boolean flags as arguments, which as positional parameters can be quite unreadable.


Leave a Reply

Your email address will not be published. Required fields are marked *