Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

dotproto commented Nov 29, 2017

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.