Skip to content

Instantly share code, notes, and snippets.

@dotproto
Created November 22, 2017 01:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/f7b97e8ff57e86e0cc39df889b6ce2bb to your computer and use it in GitHub Desktop.
Save dotproto/f7b97e8ff57e86e0cc39df889b6ce2bb to your computer and use it in GitHub Desktop.
Short collection of thoughts on a couple different approaches for default "options" values in a function
// Static defaults
function fn({a = 1, b = 2} = {}) {
return `${a}, ${b}`
}
fn() // 1, 2
fn({b: 'beta'}) // 1, beta
/**
* Pros
* + No other objects to modify/update
* + Signature explicitly states the defaults
*
*
* Cons
* - Harder to externalize defaults than other approaches
*
*/
// -----------------------------------------------------------------------------
// Externalized - explicit
let fnDefaults = {a: 1, b: 2};
function fn1({a = fnDefaults.a, b = fnDefaults.b} = {}) {
return `${a}, ${b}`
}
fn() // 1, 2
fn({b: 'beta'}) // 1, beta
/**
* Pros
* + All default logic is contained in the params
* + Brittle: Changing defaults means that unexpected object changes will be
* be caught by the compiler
*
* Cons
* - function signature gets cluttered after only a couple defaults
* - Any default change must be applied in at least 2 locations, possibly more:
* this feels boilerplate-y
* -
*/
// -----------------------------------------------------------------------------
// Externalized - implicit
// May want to deep-freeze this object
let fnDefaults = {a: 1, b: 2};
function fn(options = {}) {
let {a, b} = {...fnDefaults, ...options}
return `${a}, ${b}`
}
fn() // 1, 2
fn({b: 'beta'}) // 1, beta
/**
* Pros
* + Defaults can be data-driven
* + Don't have to enumerate defaults by hand
* + IMO this snippet reads pretty clearly
*
* Cons
* -
* - Depending on the engine, this may have more overhead (instructions, memory)
* than other approaches. I didn't confirm this
* - Function signature doesn't have any info about the expected params
* - You could write the signature as `fn(options = fnDefaults)`
*
*/
@dotproto
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment