How to use options object in functions?

Image for post
Image for post

Standard way of creating functions and passing parameters is simply to declare a function name and list parameters in the bracket:

This works well and there is absolutely nothing wrong with such a function.

However, when we pass more parameters to our function and/or we start adding optional parameters, things can become awkward to use:

First of all we have to remember the order of parameters. Obviously, all modern days IDEs will help us a bit. Yet, it’s still confusing when we simply look at the code:

We can easily change all our functions to use options object. Let’s rewrite function bar:

What we used here is destructuring assignment. In theory and practice we could have done this straight inside the bracket:

However, when we check how this is shown in, for example, Visual Studio Code then we will see IntelliSense displaying this:

Image for post
Image for post

We see the function signature with all parameters, followed by the same parameters and their type.

Therefore, if we use move destructuring to the next line and simply use options in function signature:

Image for post
Image for post

Okay, that doesn’t look like an improvement… yet. Let’s just add proper JSDoc:

Now, let’s look at IntelliSense:

Image for post
Image for post

This looks much better.

Moreover, if we give our parameters meaningful names, for example:

We can call this function by passing parameters as object in any order:

Plus, the parameter name will tell us straight away what’s the value for!

This technique works well with functions that require multiple parameters. There is really little point to refactor existing code and use options when there is only one or two parameters.

Let common sense and style guides (internal, external or simply good practices) lead us. If particular function looks good and is easy to understand what parameters it’s using there, we can leave it.

However, all other functions can be easily refactored to use options object.

Written by

Programming, project management and politics

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store