Created
November 22, 2017 01:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)` | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://remysharp.com/2017/10/25/es6-default-arguments