Member-only story
How to use options object in functions?
Standard way of creating functions and passing parameters is simply to declare a function name and list parameters in the bracket:
function foo(param) {
// do something
}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:
function bar (param1, param2, param3, optionalParam1 = true) {
// do something
}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:
zed(true, false, 5);We can easily change all our functions to use options object. Let’s rewrite function bar:
function bar (options) {
const { param1, param2, param3, optionalParam1 = true } = options;
// do something
}What we used here is destructuring assignment. In theory and practice we could have done this straight inside the bracket:
function bar ({ param1, param2, param3, optionalParam1 = true }) {
// do something
}