Skip to content

Instantly share code, notes, and snippets.

@twome
Last active March 16, 2019 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twome/303515bc112df248cd7e72aae547d3d2 to your computer and use it in GitHub Desktop.
Save twome/303515bc112df248cd7e72aae547d3d2 to your computer and use it in GitHub Desktop.
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
Copy link
Author

twome 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