Today I learnt that in Javascript, Typescript or Node, object-destructuring default-values can be function-calls
This learning assumes good knowledge of Destructuring assignment in Javascript, Typescript or Node. See these MDN docs for a foundation in this, particularly Object destructuring and default values.
Today I learnt
- A default value can be a function call, e.g.
const { foo = f() } = someObjectWhereFooIsOptional
- The function is only called if the default value is used. i.e. if the target value is undefined
Here's an example you can copy-paste into your console:
let defaultsGenerated = 0;const d = (id) => {defaultsGenerated++;return `DEFAULT_${id}`;};const { foo = d("A"), bar = d("B") } = { foo: "hello", bar: null };console.log(foo); // 'hello'console.log(bar); // 'DEFAULT_B'console.log(defaultsGenerated); // 1
Credit to Daniel Bird who just did this naturally while we were pairing, which made me 🤔