Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Clean optional parameters using destructuring
function fn(mandatoryParameter, {
optionalA = 'a value',
optionalB = 'another value',
optionalC = 'notice that this is using destructured assignment syntax, not object literal syntax'
} = {} /* unfortunately, we need to specify an empty object default if the consumer provides no object argument */){
// Configuration
this.configurationPropertyNamespace = {
optionalA,
hardCodedConfig: 'we can use the object literal "default" property naming trick to be more terse'
}
// State
Object.assign(this, { optionalB, optionalC }) // Quickly bind multiple constructor parameters straight onto the instance
// ...and now, because we used destructuring in the parameters, there is no "options" catch-all object in this
// constructor scope that we need to preface our parameters with - all the benefits of providing an object as an
// argument to a function, with none of the annoying verbosity of unpacking that object!
console.debug(optionalA, optionalB, optionalC)
}
// To call this function, we provide a "options" object as an argument as normal.
fn('a name', {
optionalA: 'a more specific value',
optionalB: 2,
optionalC: new Date()
})
// Here's that technique again as tersely as possible:
let newFn = ({
prop = 'a value'
}={}) => prop
// This is more verbose than using traditional, array-position-based parameters, but the benefit is that you never have to remember the (often quite arbitrary) parameter order of a function in order to use it.
@twome

This comment has been minimized.

Copy link
Owner Author

commented Mar 7, 2019

God I love the QOL improvements of ES6/7 so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.